package com.haoze.nurse.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.config.RedisUtil;
import com.haoze.common.exception.ServiceException;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.*;
import com.haoze.nurse.dao.*;
import com.haoze.nurse.dto.*;
import com.haoze.nurse.enumeration.*;
import com.haoze.nurse.feign.AssessmentScaleService;
import com.haoze.nurse.feign.UserDeptService;
import com.haoze.nurse.model.*;
import com.haoze.nurse.service.JwtService;
import com.haoze.nurse.service.NurseFileService;
import com.haoze.nurse.service.NurseOrderService;
import com.haoze.nurse.service.NurseStatisticsService;
import com.haoze.nurse.vo.NurseBook;
import com.haoze.nurse.vo.NurseFile;
import com.haoze.nurse.vo.NurseFileData;
import com.haoze.repository.model.ListTreeEntity;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.DigestUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class NurseFileServiceImpl implements NurseFileService {

    private static final Logger logger = LoggerFactory.getLogger(NurseFileServiceImpl.class);

    @Resource
    private NurseFileMapper emrFileMapper;

    @Resource
    NurseFileMapper nurseFileMapper;

    @Resource
    NurseFileIndexMapper nurseFileIndexMapper;

    @Resource
    NurseFileDataMapper nurseFileDataMapper;

    @Resource
    NurseFileDataDetailMapper nurseFileDataDetailMapper;

    @Resource
    NurseStatisticsService nurseStatisticsService;

    @Resource
    NurseStatisticsMapper nurseStatisticsMapper;

    @Resource
    NursePatientMapper nursePatientMapper;

    @Resource
    NurseElementMapper nurseElementMapper;

    @Resource
    NurseTransMapper nurseTransMapper;

    @Resource
    MessageMapper messageMapper;

    @Autowired
    JwtService jwtService;

    @Autowired
    HttpServletRequest request; //这里可以获取到request

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    NurseOrderService nurseOrderService;

    @Resource
    private NurseCatalogMapper nurseCatalogMapper;

    @Resource
    NurseModifyLocationMapper nurseModifyLocationMapper;

    @Resource
    private EmrMedicalCatalogMapper emrMedicalCatalogMapper;

    @Resource
    private UserDeptService userDeptService;

    @Resource
    private RedisUtil redisUtil;

    @Value("${spring.profiles.active}")
    private String activeProfile;

    @Resource(name = "taskExecutor")
    private Executor taskExecutor;

    @Autowired
    private PatientTemperatureMapper patientTemperatureMapper;

    @Autowired
    private AssessmentScaleService assessmentScaleService;


    private static String longNumStr = "①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿";

    private static SimpleDateFormat hhmm = new SimpleDateFormat("HH:mm");
    private static List<String> times = Arrays.asList("02:00", "06:00", "10:00", "14:00", "18:00", "22:00");
    private static Pattern pattern = Pattern.compile("^\\d+(\\.\\d{1})?$");


    /**
     * 新增记录获取表单初始值
     *
     * @param inpatNum   住院编号
     * @param recordType 表单类型
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result createNewRecord(String inpatNum, String recordType) {
        if (inpatNum.isEmpty() || recordType.isEmpty()) {
            return ResultGenerator.genOkResult("参数不能为空");
        }

        String tplId = "";

        if (recordType.equals(NurseFileTypeEnum.Care.getEnumValue())) {
            // 护理记录单
            tplId = nurseFileMapper.queryTplIdByVarCode("hlwsmb");
        } else if (recordType.equals(NurseFileTypeEnum.Wait.getEnumValue())) {
            // 待产记录
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbdcjl");
        } else if (recordType.equals(NurseFileTypeEnum.LabourA.getEnumValue())) {
            // 产时一
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbcsyjl");
        } else if (recordType.equals(NurseFileTypeEnum.LabourB.getEnumValue())) {
            // 产时二
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbcsejl");
        } else if (recordType.equals(NurseFileTypeEnum.Neonatus.getEnumValue())) {
            // 新生儿
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbmytsjl");
        } else if (recordType.equals(NurseFileTypeEnum.Oxytocin.getEnumValue())) {
            // 缩宫素
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbsgsycjl");
        } else if (recordType.equals(NurseFileTypeEnum.Induction.getEnumValue())) {
            // 中期引产
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbzqyc");
        } else if (recordType.equals(NurseFileTypeEnum.LabourBwatch.getEnumValue())) {
            // 产时二产后观察
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbcsechgc");
        } else if (recordType.equals(NurseFileTypeEnum.InductionWatch.getEnumValue())) {
            // 中期引产产后观察
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbzqycchgc");
        } else if (recordType.equals(NurseFileTypeEnum.InductionWait.getEnumValue())) {
            // 中期引产待产记录
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbzqycdc");
        } else if (recordType.equals(NurseFileTypeEnum.ApgarScore.getEnumValue())) {
            // 中期引产待产记录
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbapgar");
        } else if (recordType.equals(NurseFileTypeEnum.BradenScore.getEnumValue())) {
            // 中期引产待产记录
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbbraden");
        } else if (recordType.equals(NurseFileTypeEnum.PediatricGeneralCareRecord.getEnumValue())) {
            // 儿科一般护理记录单
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbekhljl");
        } else if (recordType.equals(NurseFileTypeEnum.NewbornCareRecord.getEnumValue())) {
            // 新生儿护理记录单
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbxsehljl");
        } else if (recordType.equals(NurseFileTypeEnum.CareRemark.getEnumValue())) {
            // 护理记录单备注
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_careremark");
        } else if (recordType.equals(NurseFileTypeEnum.NewCareRemark.getEnumValue())) {
            // 新生儿护理记录单备注
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_newcareremark");
        } else if (recordType.equals(NurseFileTypeEnum.ChildCareRemark.getEnumValue())) {
            // 儿科护理记录单备注
            tplId = nurseFileMapper.queryTplIdByVarCode("ck_childcareremark");
        } else if (recordType.equals(NurseFileTypeEnum.NurseCydj.getEnumValue())) {
            // 产婴登记
            tplId = nurseFileMapper.queryTplIdByVarCode("nurse_cydj");
        } else {
            // 其他
            return ResultGenerator.genOkResult(new ArrayList<>());
        }
        // 第一次点击新建会创建主文书记录
        NurseFileIndexEntity fileIndexEntity = nurseFileIndexMapper.queryIndexByRecordType(recordType, inpatNum);
        String nursefiledataid = "";
        if (fileIndexEntity == null) {
            fileIndexEntity = new NurseFileIndexEntity();
            fileIndexEntity.setFileIndexId(UUIDUtil.randomString());
            fileIndexEntity.setDataVersion(1);
            fileIndexEntity.setHospitalId("");
            fileIndexEntity.setTplId(tplId);
            fileIndexEntity.setRecordType(recordType);
            fileIndexEntity.setInpatNum(inpatNum);
            fileIndexEntity.setNurseCustomizeExpand("");
            String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
            fileIndexEntity.setCreateId(userId == null ? "创建人ID" : userId);
            Map<String, String> currentUser = getCurrentUser();
            String userName = currentUser.get("userName");
            if (StringUtils.isBlank(userName)) {
                userName = "无名";
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
            String tplName = nurseFileMapper.getTplNameByTplId(tplId);
            String fileName = tplName + "—" + userName + "—" + sdf.format(new Date(System.currentTimeMillis()));
            fileIndexEntity.setNurseFileName(fileName);
            nurseFileIndexMapper.insert(fileIndexEntity);

        }

//        // 如果类型为护理记录单则创建护理备注模板记录
//        // 创建当前患者的备注记录
//        createRemarkRecord(recordType, inpatNum);

        List<EmrTemplateDetailEntity> tplDetails = nurseFileMapper.queryTplDetailByTplId(tplId);

        List list = getNurseFileData(tplDetails, inpatNum, recordType);
        List<NurseFileData> fileDatalist = createBuildTreeData(list, null);

        // 模板会多包装一层，提出
        NurseFileData parentNurseFileData = fileDatalist.get(0);

        NurseDto nurseDto = new NurseDto();
        nurseDto.setFileDataId("");
        nurseDto.setRecordTime(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm"));
        nurseDto.setEmrFileDataList(parentNurseFileData.getEmrFileDataList());

        NursePatientMsgDTO dto = nursePatientMapper.getPatientInfo(inpatNum);
//        if (dto==null)
//            return ResultGenerator.genFailedResult("未获取到个人信息");
        // 返回床号病区科室信息
        Map<String, String> locationMap = getInHospitalLocationInfo(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm"), inpatNum, dto == null ? null : dto.getBedNo());
        String wardName = nurseFileMapper.queryDeptNameById(locationMap.get("wardId"));
        String deptName = nurseFileMapper.queryDeptNameById(locationMap.get("deptId"));
        String bedNo = locationMap.get("bedNo");

        nurseDto.setCurrBed(StringUtils.isBlank(bedNo) ? "0" : bedNo);
        nurseDto.setCurrWard(StringUtils.isBlank(wardName) ? "" : wardName);
        nurseDto.setCurrDept(StringUtils.isBlank(deptName) ? "" : deptName);
        nurseDto.setBedNo(StringUtils.isBlank(bedNo) ? "0" : bedNo);
        // 处理床号,当出院病人床号为0时显示最近一次护理记录单中记录的床号
        if ("0".equals(nurseDto.getBedNo())) {
            // 获取记录时间最近的护理记录，从中获取床号
            bedNo = nurseFileMapper.getLatestBedNo(inpatNum);
            if (StringUtils.isNotEmpty(bedNo)) {
                nurseDto.setBedNo(bedNo);
                nurseDto.setCurrBed(bedNo);
            }

        }
        nurseDto.setFileIndexId(fileIndexEntity.getFileIndexId());
        return ResultGenerator.genOkResult(nurseDto);

    }


    /**
     * 保存及患者独立表单类型的编辑保存
     *
     * @param nurseFile
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result save(NurseFile nurseFile) {

        try {
            // infoInpatNum用于记录获取个人信息的住院号，当是Apgar评分时，住院号使用母亲住院号
            String infoInpatNum = nurseFile.getInpatNum();
            if (nurseFile.getRecordType().equals(NurseFileTypeEnum.ApgarScore.getEnumValue())) {
                infoInpatNum = nurseFile.getMotherInpatNum();
            }

            // 时间添加范围判断recordTime 在入院后当前时间前包含入院时间和当前时间
            Map<String, String> patientInfo = nursePatientMapper.queryPatientInfo(infoInpatNum);
            if (patientInfo == null) {
                throw new ServiceException("住院信息不存在，无法创建记录。");
            }

            String currDateTime = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm");
            if (nurseFile.getRecordTime().compareTo(patientInfo.get("inDatetime")) < 0) {
                // 记录时间小于入院时间,不符合规范
                throw new ServiceException("记录时间不能小于入院时间。");
            }

            if (currDateTime.compareTo(nurseFile.getRecordTime()) < 0) {
                // 记录时间小于入院时间,不符合规范
                throw new ServiceException("记录时间不能超过当前时间。");
            }


            if (nurseFile.getRecordType().equals(NurseFileTypeEnum.Care.getEnumValue())
                    || nurseFile.getRecordType().equals(NurseFileTypeEnum.Wait.getEnumValue()) // 待产
                    || nurseFile.getRecordType().equals(NurseFileTypeEnum.LabourA.getEnumValue()) // 产时一
                    || nurseFile.getRecordType().equals(NurseFileTypeEnum.Neonatus.getEnumValue()) // 新生儿
                    || nurseFile.getRecordType().equals(NurseFileTypeEnum.Oxytocin.getEnumValue()) // 缩宫素
                    || nurseFile.getRecordType().equals(NurseFileTypeEnum.LabourBwatch.getEnumValue()) // 产时二产后观察
                    || nurseFile.getRecordType().equals(NurseFileTypeEnum.InductionWatch.getEnumValue()) // 中期引产产后观察
                    || nurseFile.getRecordType().equals(NurseFileTypeEnum.InductionWait.getEnumValue()) // 中期引产待产
                    || nurseFile.getRecordType().equals(NurseFileTypeEnum.BradenScore.getEnumValue()) // Braden评分
                    || nurseFile.getRecordType().equals(NurseFileTypeEnum.PediatricGeneralCareRecord.getEnumValue()) // 儿科一般护理记录单
                    || nurseFile.getRecordType().equals(NurseFileTypeEnum.NewbornCareRecord.getEnumValue())) // 新生儿护理记录单
            {
                // 全量保存
                // 1.检查当前患者是否创建待产文书，如果未创建则创建待产文书
                NurseFileIndexEntity fileIndexEntity = nurseFileIndexMapper.queryIndexByRecordType(nurseFile.getRecordType(), nurseFile.getInpatNum());
                if (fileIndexEntity == null) {
                    throw new ServiceException("当前患者的文书尚未创建");
                }

                // 2.在没有时间冲突的情况下在待产文书下创建待产记录
//            NurseFileDataEntity fileDataEntity = nurseFileDataMapper.queryOnlyRecord(nurseFile.getRecordType(), nurseFile.getInpatNum());
                NurseFileDataEntity fileDataEntity = nurseFileDataMapper.querySameTimeRecord(nurseFile.getRecordType(), nurseFile.getInpatNum(), nurseFile.getRecordTime(), "0");
                if (fileDataEntity == null) {
                    fileDataEntity = new NurseFileDataEntity();
                    fileDataEntity.setFileDataId(UUIDUtil.randomString()); //自动生成id-djh
//                    fileDataEntity.setFileDataId(nurseFile.getFileDataId());
                    fileDataEntity.setDataVersion(1);
                    fileDataEntity.setFlag("0");
                    fileDataEntity.setTplId(nurseFile.getTplId());
                    fileDataEntity.setHospitalId("");
                    fileDataEntity.setFileIndexId(fileIndexEntity.getFileIndexId());
                    fileDataEntity.setInpatNum(nurseFile.getInpatNum());
                    fileDataEntity.setRecordTime(nurseFile.getRecordTime());
                    // TODO: 创建人编号应该从请求头中获取
                    String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                            .getHeader("zuul_id");

                    fileDataEntity.setOperationId(userId == null ? "创建人ID" : userId);
                    fileDataEntity.setRecordType(nurseFile.getRecordType());
                    fileDataEntity.setCareType("0");
                    fileDataEntity.setStatisticsId("");

                    // 获取病区，科室，床号等信息
                    Map<String, String> locationInfo = getInHospitalLocationInfo(nurseFile.getRecordTime(), nurseFile.getInpatNum(), nurseFile.getBedNo());

                    fileDataEntity.setWardId(locationInfo.get("wardId"));
                    fileDataEntity.setDeptId(locationInfo.get("deptId"));
                    fileDataEntity.setBedNo(locationInfo.get("bedNo"));

                    nurseFileDataMapper.insert(fileDataEntity);


                    //调用
                    /*List<NurseFileData> collect = nurseFile.getEmrFileDataList().stream().filter(x -> StateEnum.HL_BQJHL.getValue().equals(x.getFileIndexDataEntity().getVarCode()) && "【记24小时尿量】".equals(x.getFileIndexDataEntity().getDataValue())).collect(Collectors.toList());
                    if(CollectionUtils.isNotEmpty(collect)){
                        String prevTime = DateUtil.dateToString(DateUtil.getDateBefore(DateUtil.stringToDate(nurseFile.getRecordTime()+"00","yyyy-MM-dd HH:mm:ss"),1),"yyyy-MM-dd");
                        this.computeSummary(nurseFile.getInpatNum(),prevTime);
                    }*/

                } else {
                    return ResultGenerator.genFailedResult("当前时刻已经存在记录");
                }
//
//                // 此处如果是护理记录单，那么直接根据fileDataId查出所有引用类型在4-11之间统计标记节点，删除当前人，上次记录的时间节点的关联统计记录
//                // 统计时间
//                List<String> oldStatisticsIds = nurseFileDataMapper.queryQueteType
//                if (fileDataEntity.getDataVersion()>1) {
                nurseFileDataDetailMapper.recordBeforeAndDeleteSource(fileDataEntity.getFileDataId());
//                }
                // 3.新增待产记录详情，如果有相同时间的公共数据元则更新
                for (int i = 0; i < nurseFile.getEmrFileDataList().size(); i++) {
                    NurseFileData fileData = nurseFile.getEmrFileDataList().get(i);
                    if (fileData.getElement().getName().equals("新生儿-病情、措施")) {
                        List<NurseFileData> li1 = fileData.getEmrFileDataList();  //父节点
                        for (NurseFileData nurseFileData : li1) {
                            List<NurseFileData> li2 = nurseFileData.getEmrFileDataList(); //子节点
                            String isprint = nurseFileData.getFileIndexDataEntity().getPrintIdentification(); //是否打印标志
                            if ("1".equals(isprint)) {
                                nurseFileData.getFileIndexDataEntity().setPrintIdentification("0");  //父节点修改打印标志
                                ///子节点修改打印标志
                                for (NurseFileData nurseFileData2 : li2) {
                                    String isprint2 = nurseFileData2.getFileIndexDataEntity().getPrintIdentification(); //是否打印标志
                                    if (isprint2 == null || isprint2.equals("1")) {
                                        nurseFileData2.getFileIndexDataEntity().setPrintIdentification("0");
                                    }
                                }
                            }
                        }
                    }

                    if (fileData.getElement().getName().equals("入量")) {
                        String code = fileData.getFileIndexDataEntity().getVarCode();
                        if (code == null || code.equals("") || code.equals(" ")) {
                            fileData.getFileIndexDataEntity().setVarCode("ck_jlrlbw");
                        }
                    }
                    if (fileData.getElement().getName().equals("出量")) {
                        String code = fileData.getFileIndexDataEntity().getVarCode();
                        if (code == null || code.equals("") || code.equals(" ")) {
                            fileData.getFileIndexDataEntity().setVarCode("ck_jlclbw");
                        }
                    }
                    String varCode = fileData.getElement().getVarCode();
                    if (StringUtils.isNotBlank(varCode)) {
                        String temp = fileData.getFileIndexDataEntity().getVarCode();
                        if (StringUtils.isBlank(temp)) {
                            fileData.getFileIndexDataEntity().setVarCode(fileData.getElement().getVarCode());
                        }
                    }
                    recursiveSave(fileData, fileDataEntity.getFileDataId(), nurseFile.getInpatNum(), nurseFile.getRecordType(), nurseFile.getRecordTime(), "0", i);
                }

                // 更新关联统计
                nurseStatisticsService.updateAllNeedResetStatistics(nurseFile.getInpatNum(), DateUtil.stringToDate(nurseFile.getRecordTime()), nurseFile.getRecordType());

                String summaryFileDataId = nurseFileDataMapper.querySummaryRecord(nurseFile.getInpatNum(), nurseFile.getRecordType(), nurseFile.getRecordTime());

                if (StringUtils.isNotBlank(summaryFileDataId)) {
                    Map<String, String> map1 = new HashMap<>();
                    map1.put("inpatNum", nurseFile.getInpatNum());
                    map1.put("recordTime", nurseFile.getRecordTime());
                    map1.put("fileIndexId", fileDataEntity.getFileIndexId());
                    map1.put("recordType", nurseFile.getRecordType());
                    map1.put("changeSign", "0");
                    createInputOutputSummary(map1);
                }
                // 1标识为新增类型
                nurseFileDataDetailMapper.compareAfterUpdate(fileDataEntity.getFileDataId(), UUIDUtil.randomString(), "1", fileDataEntity.getOperationId());

                Map<String, String> map = new HashMap<>();
                map.put("fileDataId", fileDataEntity.getFileDataId());
//                String recordTime = nurseFile.getRecordTime();
//                String recordHHmm = hhmm.format(DateUtil.stringToDate(recordTime));
//                if (times.contains(recordHHmm)) {
//                    taskExecutor.execute(() -> {
//                        List<PatientTemperatureEntity> temperatureEntityList = new ArrayList<>();
//                        List<NurseFileData> emrFileDataList = nurseFile.getEmrFileDataList();
//                        emrFileDataList.parallelStream().forEach(file -> {
//                            NurseFileDataDetailEntity detail = file.getFileIndexDataEntity();
//                            if ("twzt".equals(detail.getVarCode())) {
//                                if ("不升".equals(detail.getDataValue())) {
//                                    PatientTemperatureEntity patientTemperatureEntity = new PatientTemperatureEntity();
//                                    patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                    patientTemperatureEntity.initAdd();
//                                    patientTemperatureEntity.setTemperatureType("01");
//                                    patientTemperatureEntity.setTemperatureSubType("07");
//                                    patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                    patientTemperatureEntity.setMeasurementDate(DateUtil.stringToDate(recordTime + ":00"));
//                                    patientTemperatureEntity.setInpatNum(nurseFile.getInpatNum());
//                                    if (pattern.matcher(patientTemperatureEntity.getTemperatureDegreeString()).matches()) {
//                                        patientTemperatureEntity.setTemperatureDegree(patientTemperatureEntity.getTemperatureDegreeString());
//                                    }
//                                    temperatureEntityList.add(patientTemperatureEntity);
//                                }
//                            } else if ("ck_jlfs".equals(detail.getVarCode())) {
//                                PatientTemperatureEntity patientTemperatureEntity = new PatientTemperatureEntity();
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.initAdd();
//                                patientTemperatureEntity.setTemperatureType("01");
//                                if ("口温".equals(detail.getDataValue())) {
//                                    patientTemperatureEntity.setTemperatureSubType("01");
//                                } else if ("耳温".equals(detail.getDataValue())) {
//                                    patientTemperatureEntity.setTemperatureSubType("02");
//                                } else if ("腋温".equals(detail.getDataValue())) {
//                                    patientTemperatureEntity.setTemperatureSubType("03");
//                                } else if ("肛温".equals(detail.getDataValue())) {
//                                    patientTemperatureEntity.setTemperatureSubType("04");
//                                }
//                                emrFileDataList.parallelStream().filter(tempfile -> "ck_jltw".equals(tempfile.getFileIndexDataEntity().getVarCode())).forEach(obj -> {
//                                    patientTemperatureEntity.setTemperatureDegreeString(obj.getFileIndexDataEntity().getDataValue());
//                                    patientTemperatureEntity.setTemperatureUnit(obj.getFileIndexDataEntity().getUnit());
//                                });
//
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.setMeasurementDate(DateUtil.stringToDate(recordTime + ":00"));
//                                patientTemperatureEntity.setInpatNum(nurseFile.getInpatNum());
//                                if (pattern.matcher(patientTemperatureEntity.getTemperatureDegreeString()).matches()) {
//                                    patientTemperatureEntity.setTemperatureDegree(patientTemperatureEntity.getTemperatureDegreeString());
//                                }
//                                temperatureEntityList.add(patientTemperatureEntity);
//                            } else if ("ck_jlhxpl".equals(detail.getVarCode())) {
//                                PatientTemperatureEntity patientTemperatureEntity = new PatientTemperatureEntity();
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.initAdd();
//                                patientTemperatureEntity.setTemperatureType("03");
//                                patientTemperatureEntity.setTemperatureSubType("01");
//                                patientTemperatureEntity.setTemperatureDegreeString(detail.getDataValue());
//                                patientTemperatureEntity.setTemperatureUnit(detail.getUnit());
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.setMeasurementDate(DateUtil.stringToDate(recordTime + ":00"));
//                                patientTemperatureEntity.setInpatNum(nurseFile.getInpatNum());
//                                if (pattern.matcher(patientTemperatureEntity.getTemperatureDegreeString()).matches()) {
//                                    patientTemperatureEntity.setTemperatureDegree(patientTemperatureEntity.getTemperatureDegreeString());
//                                }
//                                temperatureEntityList.add(patientTemperatureEntity);
//                            } else if ("ck_jlmb".equals(detail.getVarCode())) {
//                                PatientTemperatureEntity patientTemperatureEntity = new PatientTemperatureEntity();
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.initAdd();
//                                patientTemperatureEntity.setTemperatureType("02");
//                                patientTemperatureEntity.setTemperatureSubType("01");
//                                patientTemperatureEntity.setTemperatureDegreeString(detail.getDataValue());
//                                patientTemperatureEntity.setTemperatureUnit(detail.getUnit());
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.setMeasurementDate(DateUtil.stringToDate(recordTime + ":00"));
//                                patientTemperatureEntity.setInpatNum(nurseFile.getInpatNum());
//                                if (pattern.matcher(patientTemperatureEntity.getTemperatureDegreeString()).matches()) {
//                                    patientTemperatureEntity.setTemperatureDegree(patientTemperatureEntity.getTemperatureDegreeString());
//                                }
//                                temperatureEntityList.add(patientTemperatureEntity);
//                            } else if ("hlssy".equals(detail.getVarCode())) {
//                                PatientTemperatureEntity patientTemperatureEntity = new PatientTemperatureEntity();
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.initAdd();
//                                patientTemperatureEntity.setTemperatureType("05");
//                                patientTemperatureEntity.setTemperatureSubType("07");
//                                patientTemperatureEntity.setTemperatureDegreeString(detail.getDataValue());
//                                patientTemperatureEntity.setTemperatureUnit(detail.getUnit());
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.setMeasurementDate(DateUtil.stringToDate(recordTime + ":00"));
//                                patientTemperatureEntity.setInpatNum(nurseFile.getInpatNum());
//                                if (pattern.matcher(patientTemperatureEntity.getTemperatureDegreeString()).matches()) {
//                                    patientTemperatureEntity.setTemperatureDegree(patientTemperatureEntity.getTemperatureDegreeString());
//                                }
//                                temperatureEntityList.add(patientTemperatureEntity);
//                            } else if ("hlszy".equals(detail.getVarCode())) {
//                                PatientTemperatureEntity patientTemperatureEntity = new PatientTemperatureEntity();
//                                patientTemperatureEntity.initAdd();
//                                patientTemperatureEntity.setTemperatureType("05");
//                                patientTemperatureEntity.setTemperatureSubType("05");
//                                patientTemperatureEntity.setTemperatureDegreeString(detail.getDataValue());
//                                patientTemperatureEntity.setTemperatureUnit(detail.getUnit());
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.setMeasurementDate(DateUtil.stringToDate(recordTime + ":00"));
//                                patientTemperatureEntity.setInpatNum(nurseFile.getInpatNum());
//                                if (pattern.matcher(patientTemperatureEntity.getTemperatureDegreeString()).matches()) {
//                                    patientTemperatureEntity.setTemperatureDegree(patientTemperatureEntity.getTemperatureDegreeString());
//                                }
//                                temperatureEntityList.add(patientTemperatureEntity);
//                            }
//
//                        });
//                        patientTemperatureMapper.insertBatch(temperatureEntityList);
//                    });
//                }
                return ResultGenerator.genOkResult(map);

            } else if (nurseFile.getRecordType().equals(NurseFileTypeEnum.LabourB.getEnumValue()) // 产时二
                    || nurseFile.getRecordType().equals(NurseFileTypeEnum.Induction.getEnumValue()) // 中期引产
                    || nurseFile.getRecordType().equals(NurseFileTypeEnum.ApgarScore.getEnumValue())  // Apgar评分
                    || nurseFile.getRecordType().equals(NurseFileTypeEnum.CareRemark.getEnumValue()) // 护理备注
                    || nurseFile.getRecordType().equals(NurseFileTypeEnum.NewCareRemark.getEnumValue()) // 新生儿护理备注
                    || nurseFile.getRecordType().equals(NurseFileTypeEnum.ChildCareRemark.getEnumValue()))  // 儿科护理备注
            {

                NurseFileIndexEntity fileIndexEntity = nurseFileIndexMapper.queryIndexByRecordType(nurseFile.getRecordType(), nurseFile.getInpatNum());
                if (fileIndexEntity == null) {
                    throw new ServiceException("当前患者的文书尚未创建");
                }


                // 2.产时二，中期引产这一步处理和其他类型处理不同，因为其他类型有时间限定，产时二和中期引产每个人只有一条记录
                NurseFileDataEntity fileDataEntity = nurseFileDataMapper.queryOnlyRecord(nurseFile.getRecordType(), nurseFile.getInpatNum());
//            NurseFileDataEntity fileDataEntity = nurseFileDataMapper.querySameTimeRecord(nurseFile.getRecordType(), nurseFile.getInpatNum(), nurseFile.getRecordTime());
                String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                        .getHeader("zuul_id");
                if (fileDataEntity == null) {
                    fileDataEntity = new NurseFileDataEntity();
                    fileDataEntity.setFileDataId(UUIDUtil.randomString()); //自动生成ID-djh
                    fileDataEntity.setDataVersion(1);
                    fileDataEntity.setFlag("0");
                    fileDataEntity.setTplId(nurseFile.getTplId());
                    fileDataEntity.setHospitalId("");
                    fileDataEntity.setFileIndexId(fileIndexEntity.getFileIndexId());
                    fileDataEntity.setInpatNum(nurseFile.getInpatNum());
                    fileDataEntity.setRecordTime(nurseFile.getRecordTime());
                    fileDataEntity.setRecordType(nurseFile.getRecordType());
                    fileDataEntity.setCareType("0");
                    fileDataEntity.setStatisticsId("");
                    fileDataEntity.setOperationId(userId == null ? "创建人ID" : userId);


                    // 获取病区，科室，床号等信息
                    Map<String, String> locationInfo = getInHospitalLocationInfo(nurseFile.getRecordTime(), nurseFile.getInpatNum(), nurseFile.getBedNo());

                    fileDataEntity.setWardId(locationInfo.get("wardId"));
                    fileDataEntity.setDeptId(locationInfo.get("deptId"));
                    fileDataEntity.setBedNo(locationInfo.get("bedNo"));

                    nurseFileDataMapper.insert(fileDataEntity);
                } else {

                    fileDataEntity.setDataVersion(fileDataEntity.getDataVersion() == null ? 1 : fileDataEntity.getDataVersion() + 1);
                    fileDataEntity.setRecordTime(nurseFile.getRecordTime());
                    fileDataEntity.setOperationId(userId == null ? "创建人ID" : userId);

                    // 获取病区，科室，床号等信息
                    Map<String, String> locationInfo = getInHospitalLocationInfo(nurseFile.getRecordTime(), nurseFile.getInpatNum(), nurseFile.getBedNo());

                    fileDataEntity.setWardId(locationInfo.get("wardId"));
                    fileDataEntity.setDeptId(locationInfo.get("deptId"));
                    fileDataEntity.setBedNo(locationInfo.get("bedNo"));

                    nurseFileDataMapper.update(fileDataEntity);
                }

//                if (fileDataEntity.getDataVersion()>1) {
                nurseFileDataDetailMapper.recordBeforeAndDeleteSource(fileDataEntity.getFileDataId());
//                }
                // 3.新增待产记录详情，如果有相同时间的公共数据元则更新
                for (int i = 0; i < nurseFile.getEmrFileDataList().size(); i++) {
                    NurseFileData fileData = nurseFile.getEmrFileDataList().get(i);
                    recursiveSave(fileData, fileDataEntity.getFileDataId(), nurseFile.getInpatNum(), nurseFile.getRecordType(), nurseFile.getRecordTime(), "0", i);
                }
                if (fileDataEntity.getDataVersion() == 1) {
                    nurseFileDataDetailMapper.compareAfterUpdate(fileDataEntity.getFileDataId(), UUIDUtil.randomString(), "1", fileDataEntity.getOperationId());
                } else {
                    nurseFileDataDetailMapper.compareAfterUpdate(fileDataEntity.getFileDataId(), UUIDUtil.randomString(), "2", fileDataEntity.getOperationId());
                }

                Map<String, Object> map = new HashMap<>();
                map.put("fileDataId", fileDataEntity.getFileDataId());
                map.put("fileDataEntity", fileDataEntity); //临时
                return ResultGenerator.genOkResult(map);

            }else if(nurseFile.getRecordType().equals(NurseFileTypeEnum.NurseCydj.getEnumValue())){
                //产婴登记
                // 1.检查当前患者是否创建待产文书，如果未创建则创建待产文书
                NurseFileIndexEntity fileIndexEntity = nurseFileIndexMapper.queryIndexByRecordType(nurseFile.getRecordType(), nurseFile.getInpatNum());
                if (fileIndexEntity == null) {
                    throw new ServiceException("当前患者的文书尚未创建");
                }
                NurseFileDataEntity fileDataEntity = nurseFileDataMapper.queryOnlyRecord(nurseFile.getRecordType(), nurseFile.getInpatNum());
                String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                        .getHeader("zuul_id");
                if (fileDataEntity == null) {
                    fileDataEntity = new NurseFileDataEntity();
                    fileDataEntity.setFileDataId(UUIDUtil.randomString()); //自动生成ID-djh
                    fileDataEntity.setDataVersion(1);
                    fileDataEntity.setFlag("0");
                    fileDataEntity.setTplId(nurseFile.getTplId());
                    fileDataEntity.setHospitalId("");
                    fileDataEntity.setFileIndexId(fileIndexEntity.getFileIndexId());
                    fileDataEntity.setInpatNum(nurseFile.getInpatNum());
                    fileDataEntity.setRecordTime(nurseFile.getRecordTime());
                    fileDataEntity.setRecordType(nurseFile.getRecordType());
                    fileDataEntity.setCareType("0");
                    fileDataEntity.setStatisticsId("");
                    fileDataEntity.setOperationId(userId == null ? "创建人ID" : userId);
                    // 获取病区，科室，床号等信息
                    Map<String, String> locationInfo = getInHospitalLocationInfo(nurseFile.getRecordTime(), nurseFile.getInpatNum(), nurseFile.getBedNo());
                    fileDataEntity.setWardId(locationInfo.get("wardId"));
                    fileDataEntity.setDeptId(locationInfo.get("deptId"));
                    fileDataEntity.setBedNo(locationInfo.get("bedNo"));
                    nurseFileDataMapper.insert(fileDataEntity);
                } else {
                    fileDataEntity.setDataVersion(fileDataEntity.getDataVersion() == null ? 1 : fileDataEntity.getDataVersion() + 1);
                    fileDataEntity.setRecordTime(nurseFile.getRecordTime());
                    fileDataEntity.setOperationId(userId == null ? "创建人ID" : userId);
                    // 获取病区，科室，床号等信息
                    Map<String, String> locationInfo = getInHospitalLocationInfo(nurseFile.getRecordTime(), nurseFile.getInpatNum(), nurseFile.getBedNo());
                    fileDataEntity.setWardId(locationInfo.get("wardId"));
                    fileDataEntity.setDeptId(locationInfo.get("deptId"));
                    fileDataEntity.setBedNo(locationInfo.get("bedNo"));
                    nurseFileDataMapper.update(fileDataEntity);
                }
                nurseFileDataDetailMapper.recordBeforeAndDeleteSource(fileDataEntity.getFileDataId());
//                }
                // 3.新增待产记录详情，如果有相同时间的公共数据元则更新
                for (int i = 0; i < nurseFile.getEmrFileDataList().size(); i++) {
                    NurseFileData fileData = nurseFile.getEmrFileDataList().get(i);
                    recursiveSave(fileData, fileDataEntity.getFileDataId(), nurseFile.getInpatNum(), nurseFile.getRecordType(), nurseFile.getRecordTime(), "0", i);
                }
                if (fileDataEntity.getDataVersion() == 1) {
                    nurseFileDataDetailMapper.compareAfterUpdate(fileDataEntity.getFileDataId(), UUIDUtil.randomString(), "1", fileDataEntity.getOperationId());
                } else {
                    nurseFileDataDetailMapper.compareAfterUpdate(fileDataEntity.getFileDataId(), UUIDUtil.randomString(), "2", fileDataEntity.getOperationId());
                }

                Map<String, Object> map = new HashMap<>();
                map.put("fileDataId", fileDataEntity.getFileDataId());
                map.put("fileDataEntity", fileDataEntity); //临时
                return ResultGenerator.genOkResult(map);
            }else {
                // 其他
                return ResultGenerator.genOkResult(new ArrayList<>());
            }
        } catch (Exception e) {
            NurseFileTypeEnum typeEnum = null;
            for (NurseFileTypeEnum enumTemp : NurseFileTypeEnum.values()) {
                if (nurseFile.getRecordType().equals(enumTemp.getEnumValue())) {
                    typeEnum = enumTemp;
                    break;
                }
            }
            logger.error("保存{}出错。", typeEnum == null ? "" : typeEnum.getEnumName(), e);
            // 强制事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultGenerator.genFailedResult(e.getMessage());
        }

    }

    /**
     * 编辑保存
     *
     * @param nurseFile
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result editSave(NurseFile nurseFile) {
        try {
            long t0 = System.currentTimeMillis();
            // infoInpatNum用于记录获取个人信息的住院号，当是Apgar评分时，住院号使用母亲住院号
            String infoInpatNum = nurseFile.getInpatNum();
            if (nurseFile.getRecordType().equals(NurseFileTypeEnum.ApgarScore.getEnumValue())) {
                infoInpatNum = nurseFile.getMotherInpatNum();
            }

            // 时间添加范围判断recordTime 在入院后当前时间前包含入院时间和当前时间
            Map<String, String> patientInfo = nursePatientMapper.queryPatientInfo(infoInpatNum);
            if (patientInfo == null) {
                throw new ServiceException("住院信息不存在，无法修改记录。");
            }

            String currDateTime = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm");
            if (nurseFile.getRecordTime().compareTo(patientInfo.get("inDatetime")) < 0) {
                // 记录时间小于入院时间,不符合规范
                throw new ServiceException("记录时间不能小于入院时间。");
            }

            if (currDateTime.compareTo(nurseFile.getRecordTime()) < 0) {
                // 记录时间小于入院时间,不符合规范
                throw new ServiceException("记录时间不能超过当前时间。");
            }

            // 护理记录，待产，产时一，缩宫素，新生儿，产时二产后观察，中期引产产后观察，中期引产待产
//            Timestamp currentTime = new Timestamp(System.currentTimeMillis());

            // NurseFileDataEntity fileDataEntity = nurseFileDataMapper.querySameTimeRecord(nurseFile.getRecordType(), nurseFile.getInpatNum(), nurseFile.getRecordTime());

            NurseFileDataEntity fileDataEntity = nurseFileDataMapper.queryOneDataRecord(nurseFile.getFileDataId());
            String lastRecordTime = "";
            if (fileDataEntity == null) {
                // 提示内容 2019-08-26 17:26已经存在待产记录
                return ResultGenerator.genOkResult("记录不存在");
            } else {
                // 保留上次记录时间
                lastRecordTime = fileDataEntity.getRecordTime();

                if (!fileDataEntity.getRecordTime().equals(nurseFile.getRecordTime())) {
                    // 查询变更后时刻是否存在记录，如果已经存在则不能创建
                    NurseFileDataEntity timeFileDataEntity = nurseFileDataMapper.querySameTimeRecord(nurseFile.getRecordType(), nurseFile.getInpatNum(), nurseFile.getRecordTime(), "0");
                    if (timeFileDataEntity != null && !timeFileDataEntity.getFileDataId().equals(fileDataEntity.getFileDataId()))
                        return ResultGenerator.genFailedResult("当前时刻已经存在记录");


                } else {

                }

                fileDataEntity.setDataVersion(fileDataEntity.getDataVersion() == null ? 1 : fileDataEntity.getDataVersion() + 1);
                fileDataEntity.setRecordTime(nurseFile.getRecordTime());
                fileDataEntity.setFileDataId(nurseFile.getFileDataId());
                String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
                fileDataEntity.setOperationId(userId == null ? "创建人ID" : userId); // 获取当前用户ID
                //fileDataEntity.setOperationId("编辑人ID" + fileDataEntity.getDataVersion()); // 获取当前用户ID

                // 获取病区，科室，床号等信息
                Map<String, String> locationInfo = getInHospitalLocationInfo(nurseFile.getRecordTime(), nurseFile.getInpatNum(), nurseFile.getBedNo());

                fileDataEntity.setWardId(locationInfo.get("wardId"));
                fileDataEntity.setDeptId(locationInfo.get("deptId"));
                fileDataEntity.setBedNo(locationInfo.get("bedNo"));

                // 先更新原表数据，再备份到BACK（保证更新到备份表的记录是最新编辑过的）
                nurseFileDataMapper.update(fileDataEntity);

            }

            if (fileDataEntity.getDataVersion() > 1) {
                nurseFileDataDetailMapper.recordBeforeAndDeleteSource(fileDataEntity.getFileDataId());
            }

            if (StringUtils.isNotBlank(lastRecordTime)) {
                // 删除患者统计endTime = lastRecordTime的所有统计记录
                nurseStatisticsMapper.deleteStatisticsByNodeTime(nurseFile.getInpatNum(), lastRecordTime);
                // 更新所有时间 startTime <= lastRecordTime < endTime的统计记录（包含了统计范围包含此记录历史记录和此记录历史统计记录的后一条记录）
                long t2 = System.currentTimeMillis();
                nurseStatisticsService.updateAllNeedResetStatistics(nurseFile.getInpatNum(), DateUtil.stringToDate(lastRecordTime), nurseFile.getRecordType());
                long t3 = System.currentTimeMillis();
                logger.info("第一次更新统计总耗时： {} ms", t3 - t2);
            }

            // 3.新增待产记录详情，如果有相同时间的公共数据元则更新
            for (int i = 0; i < nurseFile.getEmrFileDataList().size(); i++) {
                NurseFileData fileData = nurseFile.getEmrFileDataList().get(i);
                recursiveEditSave(fileData, fileDataEntity.getFileDataId(), nurseFile.getInpatNum(), nurseFile.getRecordType(), nurseFile.getRecordTime(), "0", i);
            }

            long t4 = System.currentTimeMillis();
            // 更新关联统计
            nurseStatisticsService.updateAllNeedResetStatistics(nurseFile.getInpatNum(), DateUtil.stringToDate(nurseFile.getRecordTime()), nurseFile.getRecordType());
            long t5 = System.currentTimeMillis();
            logger.info("第二次更新统计总耗时： {} ms", t5 - t4);

            String summaryFileDataId = nurseFileDataMapper.querySummaryRecord(nurseFile.getInpatNum(), nurseFile.getRecordType(), nurseFile.getRecordTime());

            if (StringUtils.isNotBlank(summaryFileDataId)) {
                Map<String, String> map1 = new HashMap<>();
                map1.put("inpatNum", nurseFile.getInpatNum());
                map1.put("recordTime", nurseFile.getRecordTime());
                map1.put("fileIndexId", fileDataEntity.getFileIndexId());
                map1.put("recordType", nurseFile.getRecordType());
                map1.put("changeSign", "0");

                createInputOutputSummary(map1);
            }
            nurseFileDataDetailMapper.compareAfterUpdate(fileDataEntity.getFileDataId(), UUIDUtil.randomString(), "2", fileDataEntity.getOperationId());

            Map<String, String> map = new HashMap<>();
            map.put("fileDataId", fileDataEntity.getFileDataId());

            long t1 = System.currentTimeMillis();
            logger.info("编辑记录总耗时： {} ms", t1 - t0);

//            if ("0".equals(nurseFile.getRecordType())) {
//                String recordTime = nurseFile.getRecordTime();
//                String recordHHmm = hhmm.format(DateUtil.stringToDate(recordTime));
//                if (times.contains(recordHHmm)) {
//                    taskExecutor.execute(() -> {
//                        List<PatientTemperatureEntity> temperatureEntityList = new ArrayList<>();
//                        List<NurseFileData> emrFileDataList = nurseFile.getEmrFileDataList();
//                        emrFileDataList.parallelStream().forEach(file -> {
//                            NurseFileDataDetailEntity detail = file.getFileIndexDataEntity();
//                            if ("twzt".equals(detail.getVarCode())) {
//                                if ("不升".equals(detail.getDataValue())) {
//                                    PatientTemperatureEntity patientTemperatureEntity = new PatientTemperatureEntity();
//                                    patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                    patientTemperatureEntity.initAdd();
//                                    patientTemperatureEntity.setTemperatureType("01");
//                                    patientTemperatureEntity.setTemperatureSubType("07");
//                                    patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                    patientTemperatureEntity.setMeasurementDate(DateUtil.stringToDate(recordTime + ":00"));
//                                    patientTemperatureEntity.setInpatNum(nurseFile.getInpatNum());
//                                    if (pattern.matcher(patientTemperatureEntity.getTemperatureDegreeString()).matches()) {
//                                        patientTemperatureEntity.setTemperatureDegree(patientTemperatureEntity.getTemperatureDegreeString());
//                                    }
//                                    temperatureEntityList.add(patientTemperatureEntity);
//                                }
//                            } else if ("ck_jlfs".equals(detail.getVarCode())) {
//                                PatientTemperatureEntity patientTemperatureEntity = new PatientTemperatureEntity();
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.initAdd();
//                                patientTemperatureEntity.setTemperatureType("01");
//                                if ("口温".equals(detail.getDataValue())) {
//                                    patientTemperatureEntity.setTemperatureSubType("01");
//                                } else if ("耳温".equals(detail.getDataValue())) {
//                                    patientTemperatureEntity.setTemperatureSubType("02");
//                                } else if ("腋温".equals(detail.getDataValue())) {
//                                    patientTemperatureEntity.setTemperatureSubType("03");
//                                } else if ("肛温".equals(detail.getDataValue())) {
//                                    patientTemperatureEntity.setTemperatureSubType("04");
//                                }
//                                emrFileDataList.parallelStream().filter(tempfile -> "ck_jltw".equals(tempfile.getFileIndexDataEntity().getVarCode())).forEach(obj -> {
//                                    patientTemperatureEntity.setTemperatureDegreeString(obj.getFileIndexDataEntity().getDataValue());
//                                    patientTemperatureEntity.setTemperatureUnit(obj.getFileIndexDataEntity().getUnit());
//                                });
//
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.setMeasurementDate(DateUtil.stringToDate(recordTime + ":00"));
//                                patientTemperatureEntity.setInpatNum(nurseFile.getInpatNum());
//                                if (pattern.matcher(patientTemperatureEntity.getTemperatureDegreeString()).matches()) {
//                                    patientTemperatureEntity.setTemperatureDegree(patientTemperatureEntity.getTemperatureDegreeString());
//                                }
//                                temperatureEntityList.add(patientTemperatureEntity);
//                            } else if ("ck_jlhxpl".equals(detail.getVarCode())) {
//                                PatientTemperatureEntity patientTemperatureEntity = new PatientTemperatureEntity();
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.initAdd();
//                                patientTemperatureEntity.setTemperatureType("03");
//                                patientTemperatureEntity.setTemperatureSubType("01");
//                                patientTemperatureEntity.setTemperatureDegreeString(detail.getDataValue());
//                                patientTemperatureEntity.setTemperatureUnit(detail.getUnit());
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.setMeasurementDate(DateUtil.stringToDate(recordTime + ":00"));
//                                patientTemperatureEntity.setInpatNum(nurseFile.getInpatNum());
//                                if (pattern.matcher(patientTemperatureEntity.getTemperatureDegreeString()).matches()) {
//                                    patientTemperatureEntity.setTemperatureDegree(patientTemperatureEntity.getTemperatureDegreeString());
//                                }
//                                temperatureEntityList.add(patientTemperatureEntity);
//                            } else if ("ck_jlmb".equals(detail.getVarCode())) {
//                                PatientTemperatureEntity patientTemperatureEntity = new PatientTemperatureEntity();
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.initAdd();
//                                patientTemperatureEntity.setTemperatureType("02");
//                                patientTemperatureEntity.setTemperatureSubType("01");
//                                patientTemperatureEntity.setTemperatureDegreeString(detail.getDataValue());
//                                patientTemperatureEntity.setTemperatureUnit(detail.getUnit());
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.setMeasurementDate(DateUtil.stringToDate(recordTime + ":00"));
//                                patientTemperatureEntity.setInpatNum(nurseFile.getInpatNum());
//                                if (pattern.matcher(patientTemperatureEntity.getTemperatureDegreeString()).matches()) {
//                                    patientTemperatureEntity.setTemperatureDegree(patientTemperatureEntity.getTemperatureDegreeString());
//                                }
//                                temperatureEntityList.add(patientTemperatureEntity);
//                            } else if ("hlssy".equals(detail.getVarCode())) {
//                                PatientTemperatureEntity patientTemperatureEntity = new PatientTemperatureEntity();
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.initAdd();
//                                patientTemperatureEntity.setTemperatureType("05");
//                                patientTemperatureEntity.setTemperatureSubType("07");
//                                patientTemperatureEntity.setTemperatureDegreeString(detail.getDataValue());
//                                patientTemperatureEntity.setTemperatureUnit(detail.getUnit());
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.setMeasurementDate(DateUtil.stringToDate(recordTime + ":00"));
//                                patientTemperatureEntity.setInpatNum(nurseFile.getInpatNum());
//                                if (pattern.matcher(patientTemperatureEntity.getTemperatureDegreeString()).matches()) {
//                                    patientTemperatureEntity.setTemperatureDegree(patientTemperatureEntity.getTemperatureDegreeString());
//                                }
//                                temperatureEntityList.add(patientTemperatureEntity);
//                            } else if ("hlszy".equals(detail.getVarCode())) {
//                                PatientTemperatureEntity patientTemperatureEntity = new PatientTemperatureEntity();
//                                patientTemperatureEntity.initAdd();
//                                patientTemperatureEntity.setTemperatureType("05");
//                                patientTemperatureEntity.setTemperatureSubType("05");
//                                patientTemperatureEntity.setTemperatureDegreeString(detail.getDataValue());
//                                patientTemperatureEntity.setTemperatureUnit(detail.getUnit());
//                                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
//                                patientTemperatureEntity.setMeasurementDate(DateUtil.stringToDate(recordTime + ":00"));
//                                patientTemperatureEntity.setInpatNum(nurseFile.getInpatNum());
//                                if (pattern.matcher(patientTemperatureEntity.getTemperatureDegreeString()).matches()) {
//                                    patientTemperatureEntity.setTemperatureDegree(patientTemperatureEntity.getTemperatureDegreeString());
//                                }
//                                temperatureEntityList.add(patientTemperatureEntity);
//                            }
//
//                        });
//                        patientTemperatureMapper.insertBatch(temperatureEntityList);
//                    });
//                }
//            }
            return ResultGenerator.genOkResult(map);
        } catch (Exception e) {
            NurseFileTypeEnum typeEnum = null;
            for (NurseFileTypeEnum enumTemp : NurseFileTypeEnum.values()) {
                if (nurseFile.getRecordType().equals(enumTemp.getEnumValue())) {
                    typeEnum = enumTemp;
                    break;
                }
            }
            logger.error("编辑{}出错", typeEnum == null ? "" : typeEnum.getEnumName(), e);
            // 强制事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultGenerator.genFailedResult(e.getMessage());
        }

    }

    /**
     * 获取记录列表
     *
     * @param page       页码
     * @param size       页长
     * @param inpatNum   住院编号
     * @param recordType 表单类型
     * @return
     */
    @Override
    public Result getFileList(String page, String size, String inpatNum, String recordType, String beginTime, String endTime, String orderType) {

        long beginall = System.currentTimeMillis();

        if (StringUtils.isBlank(beginTime)) {
            beginTime = "1970-01-01 00:00";
        }
        if (StringUtils.isBlank(endTime)) {
            endTime = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm");
        }

        Integer startNum = (Integer.parseInt(page) - 1) * Integer.parseInt(size);
        Integer endNum = Integer.parseInt(page) * Integer.parseInt(size);
        long begin = System.currentTimeMillis();
        List<NurseFileDataEntity> dataEntities = nurseFileDataMapper.queryDataList(startNum, endNum, inpatNum, recordType, beginTime, endTime, orderType);
        long end = System.currentTimeMillis();
        logger.info("第一次批量检索花费：{}ms", end - begin);

        //一次把所有记录列表数据查询封装到Map集合中
        Map<String, List<NurseFileData>> allDatalist = getNurseFileDatas(dataEntities, "0", true);

        List<NurseBook> list = new ArrayList<>();
        for (NurseFileDataEntity fileDataEntity : dataEntities) {
            if (fileDataEntity.getCareType().equals("1")) {
                // 根据记录绑定的统计ID获取统计详情
                NurseStatisticsEntity nurseStatisticsEntity = nurseStatisticsMapper.queryOneById(fileDataEntity.getStatisticsId());
                List statictisRecord = new ArrayList();
                statictisRecord.add(fileDataEntity.getRecordTime());
                String[] strings = nurseStatisticsEntity.getStatisticsText().split("-");
                statictisRecord.addAll(Arrays.asList(strings));

                // 护理文书里的统计类型记录
                NurseBook nurseBook = new NurseBook();
                //List<NurseFileData> nurseFileDataList = recursiveQueryFileData(fileDataEntity.getFileDataId(), "0");
                nurseBook.setEmrFileDataList(new ArrayList<>());
                nurseBook.setFileDataId(fileDataEntity.getFileDataId());
                nurseBook.setRecordTime(fileDataEntity.getRecordTime());
                Map<String, Object> map = new HashMap<>();

                //获取当前登录用户名
                Map<String, String> currentUser = nurseFileMapper.getUser(fileDataEntity.getOperationId());
                String name = currentUser.get("userName");

                map.put("list", statictisRecord);
                map.put("userName", name);

                nurseBook.setStatisticMap(map);
                nurseBook.setCareType(fileDataEntity.getCareType());
                list.add(nurseBook);
            } else {
                NurseBook nurseBook = new NurseBook();
                // List<NurseFileData> nurseFileDataList = recursiveQueryFileData(fileDataEntity.getFileDataId(), "0", "0");

                //List<NurseFileData> datalist = recursiveQueryFileData(fileDataEntity.getFileDataId(), "0", "0", true);
                List<NurseFileData> datalist = allDatalist.get(fileDataEntity.getFileDataId());
                List<NurseFileData> nurseFileDataList = buildTreeData(datalist, "0");
                nurseBook.setEmrFileDataList(nurseFileDataList);
                nurseBook.setFileDataId(fileDataEntity.getFileDataId());
                nurseBook.setRecordTime(fileDataEntity.getRecordTime());
                nurseBook.setCareType(fileDataEntity.getCareType());
                list.add(nurseBook);
            }

        }
        if (NurseFileTypeEnum.LabourBwatch.getEnumValue().equals(recordType) || NurseFileTypeEnum.InductionWatch.getEnumValue().equals(recordType)) {
            list.sort(Comparator.comparing(NurseBook::getRecordTime));
        }
        Integer sum = nurseFileDataMapper.queryDataListSum(inpatNum, recordType, beginTime, endTime);
        NurseBookDTO nurseBookDTO = new NurseBookDTO();
        nurseBookDTO.setList(list);
        nurseBookDTO.setTotal(sum);

        long endall = System.currentTimeMillis();
        logger.info("总共花费{}ms", endall - beginall);

        return ResultGenerator.genOkResult(nurseBookDTO);
    }


    /**
     * 获取打印列表
     *
     * @param page
     * @param size
     * @param inpatNum
     * @param recordType
     * @return
     */
    @Override
    public Result getPrintFileList(String page, String size, String inpatNum, String recordType, String beginTime, String endTime) {
        if (StringUtils.isBlank(beginTime)) {
            beginTime = "1970-01-01 00:00";
        }
        if (StringUtils.isBlank(endTime)) {
            endTime = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm");
        }

        Integer startNum = (Integer.parseInt(page) - 1) * Integer.parseInt(size);
        Integer endNum = Integer.parseInt(page) * Integer.parseInt(size);
        List<NurseFileDataEntity> dataEntities = nurseFileDataMapper.queryPrintDataList(startNum, endNum, inpatNum, recordType, beginTime, endTime);
        //一次把所有记录列表数据查询封装到Map集合中
        Map<String, List<NurseFileData>> allDatalist = getNurseFileDatas(dataEntities, "0", true);
        List list = new ArrayList<>();
        for (NurseFileDataEntity fileDataEntity : dataEntities) {
            // 护理文书里的统计类型记录
            NurseBook nurseBook = new NurseBook();
            if ("1".equals(fileDataEntity.getCareType())) {
                // 根据记录绑定的统计ID获取统计详情
                NurseStatisticsEntity nurseStatisticsEntity = nurseStatisticsMapper.queryOneById(fileDataEntity.getStatisticsId());
                List statictisRecord = new ArrayList();
                statictisRecord.add(fileDataEntity.getRecordTime());
                String[] strings = nurseStatisticsEntity.getStatisticsText().split("-");
                statictisRecord.addAll(Arrays.asList(strings));
                //List<NurseFileData> nurseFileDataList = recursiveQueryFileData(fileDataEntity.getFileDataId(), "0");
                nurseBook.setEmrFileDataList(new ArrayList<>());
                nurseBook.setFileDataId(fileDataEntity.getFileDataId());
                nurseBook.setRecordTime(fileDataEntity.getRecordTime());
                Map<String, Object> map = new HashMap<>();
                map.put("list", statictisRecord);
                Map<String, String> currentUser = nurseFileMapper.getUser(fileDataEntity.getOperationId());
                String name = currentUser.get("userName");
                map.put("userName", name);
                nurseBook.setStatisticMap(map);
                nurseBook.setCareType(fileDataEntity.getCareType());
            } else {
                //List<NurseFileData> datalist = recursiveQueryFileData(fileDataEntity.getFileDataId(), "0", "1", true);
                List<NurseFileData> datalist = allDatalist.get(fileDataEntity.getFileDataId());
                List<NurseFileData> nurseFileDataList = buildTreeData(datalist, "0");
                nurseBook.setEmrFileDataList(nurseFileDataList);
                nurseBook.setFileDataId(fileDataEntity.getFileDataId());
                nurseBook.setRecordTime(fileDataEntity.getRecordTime());
                nurseBook.setCareType(fileDataEntity.getCareType());
            }
            Map<String, String> patientTransMap = nurseFileDataMapper.queryDeptNameInfo(fileDataEntity.getWardId(), fileDataEntity.getDeptId(), inpatNum);
            if (patientTransMap != null) {
                String wardName = patientTransMap.get("wardName") == null ? "" : patientTransMap.get("wardName");
                String shortWardName = patientTransMap.get("shortDeptName") == null ? wardName : patientTransMap.get("shortDeptName");
                String deptName = patientTransMap.get("deptName") == null ? "" : patientTransMap.get("deptName");
                String bedNo = fileDataEntity.getBedNo() == null ? "0" : fileDataEntity.getBedNo();
                nurseBook.setCurrWard(shortWardName);
                nurseBook.setCurrDept(deptName);
                if ("0".equals(bedNo)) {
                    if (fileDataEntity != null) {
                        nurseBook.setCurrBed(fileDataEntity.getBedNo());
                    }
                } else {
                    nurseBook.setCurrBed(bedNo);
                }
                // 截取科室名称返回
                if (deptName.contains(")")) {
                    nurseBook.setCurrDept(deptName.substring(0, deptName.indexOf(")") + 1));
                } else if (deptName.contains("）")) {
                    nurseBook.setCurrDept(deptName.substring(0, deptName.indexOf("）") + 1));
                }
            }
            list.add(nurseBook);
        }

        Integer sum = nurseFileDataMapper.queryDataListSum(inpatNum, recordType, beginTime, endTime);
        NurseBookDTO nurseBookDTO = new NurseBookDTO();
        nurseBookDTO.setList(list);
        nurseBookDTO.setTotal(sum);
        return ResultGenerator.genOkResult(nurseBookDTO);
    }

    /**
     * 一次获取层级节点所有数据
     *
     * @param dataEntities
     * @param parentId
     * @param transStatistics
     * @return
     */
    public Map<String, List<NurseFileData>> getNurseFileDatas(List<NurseFileDataEntity> dataEntities, String parentId, boolean transStatistics) {
        Map<String, List<NurseFileData>> map = new HashMap<>();
        Map<String, List<NurseFileDataDetailEntity>> map1 = new HashMap<>();
        if (CollectionUtils.isNotEmpty(dataEntities)) {
            Map<String, Object> tempMap = new HashMap<>();
            List<String> fileDataIdList = new ArrayList<>();
            for (NurseFileDataEntity nurseFileDataEntity : dataEntities) {
                String fileDataId = nurseFileDataEntity.getFileDataId();
                fileDataIdList.add(fileDataId);
            }
            tempMap.put("fileDataIdList", fileDataIdList);
            tempMap.put("parentId", parentId);

            long begin = System.currentTimeMillis();
            List<Map<String, Object>> datalist = nurseFileDataDetailMapper.queryAllDataDetailLists(tempMap);
            long end = System.currentTimeMillis();
            logger.info("第二次批量检索花费：{}ms", end - begin);

//            Element tempElement = nurseFileMapper.queryElementById(dataEntity.getElementId());
//            if (tempElement != null) {
//                element.setId(tempElement.getId());
//                element.setName(tempElement.getName());
//                element.setType(tempElement.getType());
//                element.setMax(tempElement.getMax());
//                element.setMin(tempElement.getMin());
//                element.setUnit(tempElement.getUnit() == null ? "" : tempElement.getUnit());
//                element.setElementPropertyFormat(tempElement.getElementPropertyFormat());
//            }
//            element.setVarCode(dataEntity.getVarCode());
//            element.setType(dataEntity.getElementType());
//            element.setName(element.getName() == null ? dataEntity.getDataValue() : element.getName());

            if (CollectionUtils.isNotEmpty(datalist)) {
                //对比引用数据版本
                AtomicBoolean modified = this.checkQuoteFileVersion(datalist);
                if (modified.get()) {//数据变更后重新获取数据
                    datalist = nurseFileDataDetailMapper.queryAllDataDetailLists(tempMap);
                }

                for (Map<String, Object> nfde : datalist) {
                    NurseFileDataDetailEntity detailEntity = new NurseFileDataDetailEntity();
                    Element element = new Element();
                    NurseFileData nurseFileData = new NurseFileData();

                    detailEntity.setElementId(nfde.get("elementId") == null ? "" : nfde.get("elementId").toString());
                    detailEntity.setRecordType(nfde.get("recordType") == null ? "" : nfde.get("recordType").toString());
                    detailEntity.setShowIdentification(nfde.get("showIdentification") == null ? "0" : nfde.get("showIdentification").toString());
                    detailEntity.setBondNo(nfde.get("bondNo") == null ? "0" : nfde.get("bondNo").toString());
                    detailEntity.setParentId(nfde.get("parentId") == null ? "" : nfde.get("parentId").toString());
                    detailEntity.setPrintIdentification(nfde.get("printIdentification") == null ? "0" : nfde.get("printIdentification").toString());
                    detailEntity.setRecordTime(nfde.get("recordTime") == null ? "" : nfde.get("recordTime").toString());
                    detailEntity.setDeleteIdentification(nfde.get("deleteIdentification") == null ? "0" : nfde.get("deleteIdentification").toString());
                    detailEntity.setEditIdentification(nfde.get("editIdentification") == null ? "1" : nfde.get("editIdentification").toString());
                    detailEntity.setSortId(Integer.parseInt(nfde.get("sortId") == null ? "" : nfde.get("sortId").toString()));
                    detailEntity.setElementType(nfde.get("elementType") == null ? "" : nfde.get("elementType").toString());
                    detailEntity.setTplDetailId(nfde.get("tplDetailId") == null ? "" : nfde.get("tplDetailId").toString());
                    detailEntity.setFileDataDetailId(nfde.get("fileDataDetailId").toString());
                    detailEntity.setFileDataId(nfde.get("fileDataId").toString());
                    detailEntity.setVarCode(nfde.get("varCode") == null ? "" : nfde.get("varCode").toString());
                    detailEntity.setDataCode(nfde.get("dataCode") == null ? "" : nfde.get("dataCode").toString());
                    detailEntity.setDataValue(nfde.get("dataValue") == null ? "" : nfde.get("dataValue").toString());
                    detailEntity.setUnit(nfde.get("unit") == null ? "" : nfde.get("unit").toString());
                    detailEntity.setExpandFields(nfde.get("expandFields") == null ? "{}" : nfde.get("expandFields").toString());
                    detailEntity.setQuoteType(nfde.get("quoteType") == null ? "" : nfde.get("quoteType").toString());
                    detailEntity.setQuoteId(nfde.get("quoteId") == null ? "" : nfde.get("quoteId").toString());
                    detailEntity.setQuoteDataValue(nfde.get("quoteDataValue") == null ? "" : nfde.get("quoteDataValue").toString());
                    detailEntity.setQuoteIdentify(nfde.get("quoteIdentify") == null ? "" : nfde.get("quoteIdentify").toString());
                    detailEntity.setQuoteModifiedFlag(nfde.get("quoteModifiedFlag") == null ? "" : nfde.get("quoteModifiedFlag").toString());
                    detailEntity.setInpatNum(nfde.get("inpatNum") == null ? "" : nfde.get("inpatNum").toString());
                    detailEntity.setMedicalId(nfde.get("medicalId") == null ? "" : nfde.get("medicalId").toString());

                    element.setId(detailEntity.getElementId());
                    element.setName(nfde.get("elementName") == null ? "" : nfde.get("elementName").toString());
                    element.setType(detailEntity.getElementType());
                    element.setVarCode(detailEntity.getVarCode());
                    element.setMin(Double.parseDouble(nfde.get("minValue") == null ? "0" : nfde.get("minValue").toString()));
                    element.setMax(Double.parseDouble(nfde.get("maxValue") == null ? "0" : nfde.get("maxValue").toString()));
                    element.setUnit(nfde.get("elementUnit") == null ? "" : nfde.get("elementUnit").toString());
                    element.setElementPropertyFormat(nfde.get("elementPropertyFormat") == null ? "{}" : nfde.get("elementPropertyFormat").toString());

                    nurseFileData.setFileIndexDataEntity(detailEntity);
                    nurseFileData.setElement(element);

                    if (detailEntity.getVarCode() != null &&
                            (detailEntity.getVarCode().equals("jldccl")
                                    || detailEntity.getVarCode().equals("jlxsecl")
                                    || detailEntity.getVarCode().equals("jlsgsycbz")
                                    || detailEntity.getVarCode().equals("hlbqjhl")
                                    || detailEntity.getVarCode().equals("jlcscla")
                                    || detailEntity.getVarCode().equals("jlxsecl")
                                    || detailEntity.getVarCode().equals("jlsgsycbz"))) {
                        detailEntity.setDataValue("");
                    }

                    detailEntity.setExpandFieldsMap(JSON.parseObject(detailEntity.getExpandFields() == null ? "{}" : detailEntity.getExpandFields(), Map.class));

                    // 添加统计判断 transStatistics 1转换统计，0转换统计
                    if (transStatistics && StringUtils.isNotBlank(detailEntity.getQuoteId()) && QuoteTypeEnum.Statistics.getEnumValue().equals(detailEntity.getQuoteType())) {
                        NurseStatisticsEntity statisticsEntity = nurseStatisticsMapper.queryOneById(detailEntity.getQuoteId());
                        if (statisticsEntity != null) {
                            detailEntity.setDataValue(statisticsEntity.getStatisticsText());
                        }
                    }

                    if (map.containsKey(nfde.get("fileDataId").toString())) {
                        List<NurseFileData> numberList = map.get(nfde.get("fileDataId").toString());
                        numberList.add(nurseFileData);
                    } else {
                        List numberList2 = new ArrayList<>();
                        numberList2.add(nurseFileData);
                        map.put(nfde.get("fileDataId").toString(), numberList2);
                    }
                }
//                Set<String> keys = map1.keySet();
//
//                long begin1 = System.currentTimeMillis();
//                for (String key : keys) {
//                    List<NurseFileDataDetailEntity> l = map1.get(key);
//                    if (ArrayUtils.isNotEmpty(l.toArray())) {
//                        map.put(key, convertData(l, transStatistics));
//                    }
//                }
//                long end1 = System.currentTimeMillis();
//                System.out.println("第三次加缓存处理花费："+(end1-begin1)+"毫秒！！！");

//                for (NurseFileDataDetailEntity nfde : datalist) {
//                    if (map1.containsKey(nfde.getFileDataId())) {
//                        List<NurseFileDataDetailEntity> numberList = map1.get(nfde.getFileDataId());
//                        numberList.add(nfde);
//                    } else {
//                        List<NurseFileDataDetailEntity> numberList2 = new ArrayList<>();
//                        numberList2.add(nfde);
//                        map1.put(nfde.getFileDataId(), numberList2);
//                    }
//                }
//                Set<String> keys = map1.keySet();
//
//                long begin1 = System.currentTimeMillis();
//                for (String key : keys) {
//                    List<NurseFileDataDetailEntity> l = map1.get(key);
//                    if (ArrayUtils.isNotEmpty(l.toArray())) {
//                        map.put(key, convertData(l, transStatistics));
//                    }
//                }
//                long end1 = System.currentTimeMillis();
//                System.out.println("第三次加缓存处理花费："+(end1-begin1)+"毫秒！！！");
            }
        }
        return map;
    }


    private AtomicBoolean checkQuoteFileVersion(List<Map<String, Object>> datalist) {
        List<Map<String, Object>> quoteList = datalist.stream().filter(entity -> entity.get("quoteId") != null && entity.get("quoteType") != null && NurseEnum.QUOTE_TYPE_ONE.getIndex().equals(entity.get("quoteType").toString())).collect(Collectors.toList());
        AtomicBoolean modified = new AtomicBoolean(false);
        quoteList.stream().forEach(entity -> {
            //引用病历的数据
            List<Map<String, Object>> fileIndexData = nurseFileDataDetailMapper.getFileIndexDataEntity(entity.get("quoteIdentify").toString(), entity.get("quoteId").toString());
            if (NurseEnum.QUOTE_IDENTIFY_ZERO.getIndex().equals(entity.get("quoteIdentify").toString())) {
                if (CollectionUtils.isNotEmpty(fileIndexData)) {
                    Map<String, Object> fileIndexMap = fileIndexData.get(0);
                    String dataValue = "", quoteDataValue = "";
                    try {
                        if (fileIndexMap.get("DATA_VALUE") != null) {
                            if (fileIndexMap.get("DATA_VALUE") instanceof Clob) {
                                Clob clob = (Clob) fileIndexMap.get("DATA_VALUE");
                                BufferedReader reader = new BufferedReader(clob.getCharacterStream());
                                dataValue = FileCopyUtils.copyToString(reader);
                            } else {
                                dataValue = (String) fileIndexMap.get("DATA_VALUE");
                            }
                        }
                    } catch (SQLException | IOException e) {
                        logger.error("转换对象出错。", e);
                    }
                    try {
                        if (fileIndexMap.get("QUOTE_DATA_VALUE") != null) {
                            if (fileIndexMap.get("QUOTE_DATA_VALUE") instanceof Clob) {
                                Clob clob = (Clob) fileIndexMap.get("QUOTE_DATA_VALUE");
                                BufferedReader reader = new BufferedReader(clob.getCharacterStream());
                                quoteDataValue = FileCopyUtils.copyToString(reader);
                            } else {
                                quoteDataValue = (String) fileIndexMap.get("QUOTE_DATA_VALUE");
                            }
                        }
                    } catch (SQLException | IOException e) {
                        logger.error("转换对象出错。", e);
                    }

                    if (StringUtils.isBlank(quoteDataValue)) {
                        quoteDataValue = "";
                    }
                    //病历修改过
                    if (!(entity.get("quoteDataValue") == null ? "" : entity.get("quoteDataValue").toString()).equals(quoteDataValue) &&
                            !(entity.get("quoteDataValue") == null ? "" : entity.get("quoteDataValue").toString()).equals(DigestUtils.md5DigestAsHex(quoteDataValue.getBytes()))) {
                        modified.set(true);
                        fileIndexMap.put("DATA_VALUE", dataValue);
                        fileIndexMap.put("ID", entity.get("fileDataDetailId").toString());
                        fileIndexMap.put("ELEMENT_TYPE", fileIndexMap.get("ELEMENT_TYPE"));
                        fileIndexMap.put("UNIT", fileIndexMap.get("UNIT"));
                        fileIndexMap.put("QUOTE_DATA_VALUE", DigestUtils.md5DigestAsHex(quoteDataValue.getBytes()));
                        nurseFileDataDetailMapper.updateQuoteFile(fileIndexMap);
                    }
                }
            } else {
                if (CollectionUtils.isNotEmpty(fileIndexData)) {
                    String quoteDataValue = nurseFileDataDetailMapper.getFileIndexDataValue(entity.get("quoteId").toString());
                    if (StringUtils.isBlank(quoteDataValue)) {
                        quoteDataValue = "";
                    }
                    if (!(entity.get("quoteDataValue") == null ? "" : entity.get("quoteDataValue").toString()).equals(quoteDataValue) &&
                            !(entity.get("quoteDataValue") == null ? "" : entity.get("quoteDataValue").toString()).equals(DigestUtils.md5DigestAsHex(quoteDataValue.getBytes()))) {
                        modified.set(true);
                        String parentId = entity.get("fileDataDetailId").toString();
                        nurseFileDataDetailMapper.deleteQuoteByPatentId(parentId, entity.get("fileDataId").toString());
                        Map<String, String> tempMap = new HashMap<>();
                        List<NurseFileDataDetailEntity> changed = fileIndexData.stream().map(obj -> {
                            String newId = UUIDUtil.randomString();
                            NurseFileDataDetailEntity newDetail = new NurseFileDataDetailEntity();
                            String oldId = obj.get("FILE_INDEX_DATA_ID").toString();
                            newDetail.setFileDataDetailId(newId);
                            String oldParentId = obj.get("PARENT_FILE_INDEX_DATA_ID").toString();
                            tempMap.put(oldId, newId);
                            //替换调用病程一级节点下的parentId quoteId为调用病程的父节点的id
                            if (oldParentId.equals(entity.get("quoteId").toString())) {
                                newDetail.setParentId(parentId);
                            }
                            if (tempMap.get(oldParentId) != null) {
                                newDetail.setParentId(tempMap.get(oldParentId));
                            }
                            String dataValue = "";
                            try {
                                if (obj.get("DATA_VALUE") != null) {
                                    if (obj.get("DATA_VALUE") instanceof Clob) {
                                        Clob clob = (Clob) obj.get("DATA_VALUE");
                                        BufferedReader reader = new BufferedReader(clob.getCharacterStream());
                                        dataValue = FileCopyUtils.copyToString(reader);
                                    } else {
                                        dataValue = (String) obj.get("DATA_VALUE");
                                    }
                                }
                            } catch (SQLException | IOException e) {
                                logger.error("转换对象出错。", e);
                            }
                            newDetail.setElementId(obj.get("ELEMENT_ID") == null ? "" : obj.get("ELEMENT_ID").toString());
                            newDetail.setDataCode(obj.get("DATA_CODE") == null ? "" : obj.get("DATA_CODE").toString());
                            newDetail.setDataValue(dataValue);
                            newDetail.setShowIdentification(obj.get("SHOW_IDENTIFICATION").toString());
                            newDetail.setPrintIdentification(obj.get("PRINT_IDENTIFICATION").toString());
                            newDetail.setDeleteIdentification(obj.get("DELETE_IDENTIFICATION").toString());
                            newDetail.setSortId(Integer.parseInt(obj.get("SORT_ID").toString()));
                            newDetail.setElementProperty(obj.get("ELEMENT_PROPERTY") == null ? "" : obj.get("ELEMENT_PROPERTY").toString());
                            newDetail.setElementType(obj.get("ELEMENT_TYPE") == null ? "1" : obj.get("ELEMENT_TYPE").toString());
                            newDetail.setUnit(obj.get("UNIT") == null ? "" : obj.get("UNIT").toString());
                            newDetail.setDataVersion(Integer.parseInt(entity.get("dataVersion") == null ? "1" : entity.get("dataVersion").toString()));
                            newDetail.setRecordTime(entity.get("recordTime").toString());
                            newDetail.setFileDataId(entity.get("fileDataId").toString());
                            newDetail.setQuoteType("");
                            newDetail.setQuoteId("");
                            newDetail.setQuoteIdentify("");
                            return newDetail;
                        }).collect(Collectors.toList());
                        nurseFileDataDetailMapper.insertBatch(changed);
                        nurseFileDataDetailMapper.updateQuoteFileValue(entity.get("fileDataDetailId").toString(), DigestUtils.md5DigestAsHex(quoteDataValue.getBytes()));
                    }
                }
            }
        });
        return modified;
    }


    @Override
    public Result getPrintFileSum(String inpatNum, String recordType, String beginTime, String endTime) {
        if (StringUtils.isBlank(beginTime)) {
            beginTime = "1970-01-01 00:00";
        }
        if (StringUtils.isBlank(endTime)) {
            endTime = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm");
        }

        Integer sum = nurseFileDataMapper.queryDataListSum(inpatNum, recordType, beginTime, endTime);
        if (sum == null)
            return ResultGenerator.genFailedResult("获取失败");
        return ResultGenerator.genOkResult(sum);
    }

    /**
     * 删除一条记录
     *
     * @param map
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteOneRecord(Map map) {
        String fileDataId = String.valueOf(map.get("fileDataId"));
        //String operationId = "删除人ID";
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        String operationId = userId == null ? "创建人ID" : userId;
        if (StringUtils.isBlank(fileDataId))
            return ResultGenerator.genOkResult();
        // 获取当前操作用户,操作时间
        NurseFileDataEntity entity = nurseFileDataMapper.queryOneDataRecord(fileDataId);
        if (entity == null) {
            return ResultGenerator.genFailedResult("未找到当前记录");
        }


        // 备份详情到临时表并删除详情记录
        nurseFileDataDetailMapper.recordBeforeAndDeleteSource(fileDataId);
        // 比较详情表和临时表，将删除状态记录进主记录痕迹表和详情痕迹表
        nurseFileDataDetailMapper.compareAfterUpdate(fileDataId, UUIDUtil.randomString(), "3", operationId);
        // 删除原主记录表
        nurseFileDataMapper.deleteDataRecord(fileDataId);

        // 删除患者统计endTime = lastRecordTime的所有统计记录
        nurseStatisticsMapper.deleteStatisticsByNodeTime(entity.getInpatNum(), entity.getRecordTime());

        nurseStatisticsService.updateAllNeedResetStatistics(entity.getInpatNum(), DateUtil.stringToDate(entity.getRecordTime()), entity.getRecordType());

        String summaryFileDataId = nurseFileDataMapper.querySummaryRecord(entity.getInpatNum(), entity.getRecordType(), entity.getRecordTime());

        if (StringUtils.isNotBlank(summaryFileDataId)) {
            Map<String, String> map1 = new HashMap<>();
            map1.put("inpatNum", entity.getInpatNum());
            map1.put("recordTime", entity.getRecordTime());
            map1.put("fileIndexId", entity.getFileIndexId());
            map1.put("recordType", entity.getRecordType());
            map1.put("changeSign", "0");
            createInputOutputSummary(map1);
        }
        /*else{
            if(StringUtils.isNotBlank(entity.getRecordTime())){
                String recordTime="";
                if(entity.getRecordTime().length()>10){
                    recordTime=entity.getRecordTime().substring(0,10);
                }
                String prevTime = DateUtil.dateToString(DateUtil.getDateBefore(DateUtil.stringToDate(recordTime+" 00:00:00","yyyy-MM-dd HH:mm:ss"),1),"yyyy-MM-dd");
                this.computeSummary(entity.getInpatNum(),prevTime);
            }
        }*/

        return ResultGenerator.genOkResult("删除成功");
    }


    /**
     * 获取一条记录信息
     *
     * @param fileDataId 记录ID
     * @param inpatNum   住院编号
     * @param recordType 表单类型
     * @return
     */
    @Override
    public Result getOneRecord(String fileDataId, String inpatNum, String recordType) {
        if (fileDataId != null && fileDataId.length() == 32) {

            NurseDto nurseDto = new NurseDto();
            NurseFileDataEntity fileDataEntity = nurseFileDataMapper.queryOneDataRecord(fileDataId);
            if (fileDataEntity != null) {
                nurseDto.setFileDataId(fileDataId);
                nurseDto.setRecordTime(fileDataEntity.getRecordTime());

                List<NurseFileData> datalist = recursiveQueryFileData(fileDataId, "0", "0", false);
                List<NurseFileData> nurseFileDataList = buildTreeData(datalist, "0");

                nurseDto.setEmrFileDataList(nurseFileDataList);

                // 返回床号病区科室信息
                Map<String, String> locationMap = getInHospitalLocationInfo(fileDataEntity.getRecordTime(), inpatNum, fileDataEntity.getBedNo());
                String wardName = nurseFileMapper.queryDeptNameById(locationMap.get("wardId"));
                String deptName = nurseFileMapper.queryDeptNameById(locationMap.get("deptId"));
                String bedNo = locationMap.get("bedNo");
                nurseDto.setCurrBed(bedNo == null ? "" : bedNo);
                nurseDto.setCurrWard(wardName == null ? "" : wardName);
                nurseDto.setCurrDept(deptName == null ? "" : deptName);
                nurseDto.setBedNo(bedNo == null ? "0" : bedNo);

                return ResultGenerator.genOkResult(nurseDto);
            } else {
                if (recordType.equals(NurseFileTypeEnum.CareRemark.getEnumValue())
                        || recordType.equals(NurseFileTypeEnum.NewCareRemark.getEnumValue())
                        || recordType.equals(NurseFileTypeEnum.ChildCareRemark.getEnumValue())) {

                    return ResultGenerator.genOkResult("");
                } else {
                    // 没有传入，那么返回新增接口返回数据
                    return createNewRecord(inpatNum, recordType);
                }

            }

        } else {
            NurseFileDataEntity dataEntity = nurseFileDataMapper.queryOnlyRecord(recordType, inpatNum);
            if (dataEntity != null) {

                fileDataId = dataEntity.getFileDataId();
                // 存在记录
                NurseDto nurseDto = new NurseDto();
                NurseFileDataEntity fileDataEntity = nurseFileDataMapper.queryOneDataRecord(fileDataId);
                nurseDto.setFileDataId(fileDataId);
                nurseDto.setRecordTime(fileDataEntity.getRecordTime());

                List<NurseFileData> datalist = recursiveQueryFileData(fileDataId, "0", "0", false);
                List<NurseFileData> nurseFileDataList = buildTreeData(datalist, "0");

                nurseDto.setEmrFileDataList(nurseFileDataList);

                // 返回床号病区科室信息
                Map<String, String> locationMap = getInHospitalLocationInfo(fileDataEntity.getRecordTime(), inpatNum, fileDataEntity.getBedNo());
                String wardName = nurseFileMapper.queryDeptNameById(locationMap.get("wardId"));
                String deptName = nurseFileMapper.queryDeptNameById(locationMap.get("deptId"));
                String bedNo = locationMap.get("bedNo");
                nurseDto.setCurrBed(bedNo == null ? "" : bedNo);
                nurseDto.setCurrWard(wardName == null ? "" : wardName);
                nurseDto.setCurrDept(deptName == null ? "" : deptName);
                nurseDto.setBedNo(bedNo == null ? "0" : bedNo);
                return ResultGenerator.genOkResult(nurseDto);

            }

            // 没有传入，那么返回新增接口返回数据
//            return createNewRecord(inpatNum, recordType);
            if (recordType.equals(NurseFileTypeEnum.CareRemark.getEnumValue())
                    || recordType.equals(NurseFileTypeEnum.NewCareRemark.getEnumValue())
                    || recordType.equals(NurseFileTypeEnum.ChildCareRemark.getEnumValue())) {

                return ResultGenerator.genOkResult("");
            } else {
                // 没有传入，那么返回新增接口返回数据
                return createNewRecord(inpatNum, recordType);
            }
        }
    }


    public Result queryRegisterBirthData(String inpatNum, String recordType){
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        NurseFileDataEntity fileDataEntity = nurseFileDataMapper.queryOnlyRecord(recordType,inpatNum);
        if(fileDataEntity!=null){
            String fileDataId = fileDataEntity.getFileDataId();
            //修改跳转
            if (fileDataId != null && fileDataId.length() == 32) {

                NurseDto nurseDto = new NurseDto();
                //NurseFileDataEntity fileDataEntity = nurseFileDataMapper.queryOneDataRecord(fileDataId);
                if (fileDataEntity != null) {
                    nurseDto.setFileDataId(fileDataId);
                    nurseDto.setRecordTime(fileDataEntity.getRecordTime());

                    List<NurseFileData> datalist = recursiveQueryFileData(fileDataId, "0", "0", false);
                    List<NurseFileData> nurseFileDataList = buildTreeData(datalist, "0");

                    nurseDto.setEmrFileDataList(nurseFileDataList);

                    // 返回床号病区科室信息
                    Map<String, String> locationMap = getInHospitalLocationInfo(fileDataEntity.getRecordTime(), inpatNum, fileDataEntity.getBedNo());
                    String wardName = nurseFileMapper.queryDeptNameById(locationMap.get("wardId"));
                    String deptName = nurseFileMapper.queryDeptNameById(locationMap.get("deptId"));
                    String bedNo = locationMap.get("bedNo");
                    nurseDto.setCurrBed(bedNo == null ? "" : bedNo);
                    nurseDto.setCurrWard(wardName == null ? "" : wardName);
                    nurseDto.setCurrDept(deptName == null ? "" : deptName);
                    nurseDto.setBedNo(bedNo == null ? "0" : bedNo);
                    return ResultGenerator.genOkResult(nurseDto);
                }
            }
        }else{
            NurseFileIndexEntity fileIndexEntity = nurseFileIndexMapper.queryIndexByRecordType(recordType, inpatNum);
            // 产婴登记
            String tplId = nurseFileMapper.queryTplIdByVarCode("nurse_cydj");
            String nursefiledataid = "";
            if (fileIndexEntity == null) {
                fileIndexEntity = new NurseFileIndexEntity();
                fileIndexEntity.setFileIndexId(UUIDUtil.randomString());
                fileIndexEntity.setDataVersion(1);
                fileIndexEntity.setHospitalId("");
                fileIndexEntity.setTplId(tplId);
                fileIndexEntity.setRecordType(recordType);
                fileIndexEntity.setInpatNum(inpatNum);
                fileIndexEntity.setNurseCustomizeExpand("");
                fileIndexEntity.setCreateId(userId == null ? "创建人ID" : userId);
                Map<String, String> currentUser = getCurrentUser();
                String userName = currentUser.get("userName");
                if (StringUtils.isBlank(userName)) {
                    userName = "无名";
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
                String tplName = nurseFileMapper.getTplNameByTplId(tplId);
                String fileName = tplName + "—" + userName + "—" + sdf.format(new Date(System.currentTimeMillis()));
                fileIndexEntity.setNurseFileName(fileName);
                nurseFileIndexMapper.insert(fileIndexEntity);
            }

            //根据住院号获取科室id
            NursePatientMsgDTO dto = nursePatientMapper.getPatientInfo(inpatNum);
            if(dto!=null) {
                return assessmentScaleService.scoreCreate(tplId,inpatNum,dto.getDeptId(),userId);
            }
            //新增跳转
            //return createNewRecord(inpatNum,recordType);
        }
        return ResultGenerator.genOkResult();
    }



    /**
     * 保存节点
     *
     * @param fileData
     * @param fileDataId 记录ID
     * @param inpatNum   住院编号
     * @param recordTime 记录时间
     * @param parentId   父节点ID
     * @throws Exception
     */
    private void recursiveSave(NurseFileData fileData, String fileDataId, String inpatNum, String recordType, String recordTime, String parentId, Integer sortId) throws Exception {
        // 无记录，新增
        NurseFileDataDetailEntity newDataDetailEntity = fileData.getFileIndexDataEntity();

        newDataDetailEntity.setFileDataDetailId((newDataDetailEntity.getFileDataDetailId() == null || newDataDetailEntity.getFileDataDetailId().length() != 32) ? UUIDUtil.randomString() : newDataDetailEntity.getFileDataDetailId());
        // TODO: 前端新增保存时传了上次的detailId，需要改
//        newDataDetailEntity.setFileDataDetailId(UUIDUtil.randomString());
        newDataDetailEntity.setDataVersion(newDataDetailEntity.getDataVersion() == null ? 1 : newDataDetailEntity.getDataVersion() + 1);
        newDataDetailEntity.setHospitalId("");
        newDataDetailEntity.setRecordTime(recordTime);
        newDataDetailEntity.setRecordType(recordType);
        newDataDetailEntity.setDataCode(newDataDetailEntity.getDataCode() == null ? "" : newDataDetailEntity.getDataCode());
        newDataDetailEntity.setDataValue(newDataDetailEntity.getDataValue() == null ? "" : newDataDetailEntity.getDataValue());
        newDataDetailEntity.setInpatNum(inpatNum);
        newDataDetailEntity.setElementId(fileData.getElement() == null ? "" : fileData.getElement().getId());
        newDataDetailEntity.setSortId(sortId);


        //判断elementId是否为空，同时校验值域字典
        if (StringUtils.isBlank(newDataDetailEntity.getElementId())) {
            if (StringUtils.isNotBlank(newDataDetailEntity.getDataValue())) {
                String elementId = nurseFileMapper.querySysElementId(StateEnum.MB_WB.getValue());
                if (StringUtils.isBlank(elementId)) {
                    throw new Exception(newDataDetailEntity.getDataValue() + "没有数据元id,无法保存！");
                } else {
                    newDataDetailEntity.setElementId(elementId);
                }
            } else {
                String elementId = nurseFileMapper.querySysElementId(StateEnum.MB_WB.getValue());
                if (StringUtils.isBlank(elementId)) {
                    throw new Exception(newDataDetailEntity.getDataValue() + "没有数据元id,无法保存！");
                } else {
                    newDataDetailEntity.setElementId(elementId);
                }
            }
        }

//        String varCode = fileData.getElement().getVarCode();
//        if ("shoushumingcheng".equals(varCode)) {
//            Map map = newDataDetailEntity.getExpandFieldsMap();
//            if (map == null) {
//                map = new HashMap();
//            }
//            map.put("varCode", "shoushumingcheng");
//            String expandFields = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty);
//            newDataDetailEntity.setExpandFields(expandFields);
//        }

        newDataDetailEntity.setElementType(fileData.getElement() == null ? "" : fileData.getElement().getType());
        newDataDetailEntity.setFlag("0");

        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");

        newDataDetailEntity.setOperationId(userId == null ? "创建人ID" : userId);
        newDataDetailEntity.setFileDataId(fileDataId);
        newDataDetailEntity.setParentId(parentId);

        if (newDataDetailEntity.getVarCode() != null) {
//                &&
//                (newDataDetailEntity.getVarCode().equals(StateEnum.HL_RLMC.getValue()) || newDataDetailEntity.getVarCode().equals(StateEnum.HL_XSERLMC.getValue()))) {
            String expandFields = JSON.toJSONString(newDataDetailEntity.getExpandFieldsMap(), SerializerFeature.WriteNullStringAsEmpty);
            newDataDetailEntity.setExpandFields(expandFields);
        }

        // 对于大段无VarCode节点需要将子节点内容冗余进DataValue中，方便后续比较判断数据是否变更
        if (newDataDetailEntity.getVarCode() != null &&
                (newDataDetailEntity.getVarCode().equals("jldccl")
                        || newDataDetailEntity.getVarCode().equals("jlxsecl")
                        || newDataDetailEntity.getVarCode().equals("jlsgsycbz")
                        || newDataDetailEntity.getVarCode().equals("hlbqjhl")
                        || newDataDetailEntity.getVarCode().equals("jlcscla")
                        || newDataDetailEntity.getVarCode().equals("jlxsecl")
                        || newDataDetailEntity.getVarCode().equals("jlsgsycbz"))) {
//            // 转JSON前先清除DataValue，防止多次存储
//            fileData.getFileIndexDataEntity().setDataValue("");
//            // 冗余json(方便记录对比，前端打印使用)
//            String md5 = JSON.toJSONString(fileData.getEmrFileDataList(), SerializerFeature.WriteNullStringAsEmpty);
//            String dataValueMd5 = DigestUtils.md5DigestAsHex(md5.getBytes());
//            newDataDetailEntity.setDataCode(dataValueMd5 == null ? "" : dataValueMd5);

            List<NurseFileData> fileDataTemp = fileData.getEmrFileDataList();
            String dataValueText = this.getDataValueText(fileDataTemp);
            newDataDetailEntity.setDataValue(dataValueText);
        }

        // 护理文书特殊处理出入量统计
//        List<String> statisticsTypes = new ArrayList<>(Arrays.asList("4", "5", "6", "7", "8", "9", "10", "11"));
        // 在保存前需要先进行统计标记过滤计算
        if (QuoteTypeEnum.Statistics.getEnumValue().equals(newDataDetailEntity.getQuoteType())) { // 引用属于统计类型
            // 计算统计并将统计id作为引用id保存 // TODO: 此处报错 java.lang.NullPointerException: null
            String statisticsId = nurseStatisticsService.inputOutputStatistics(inpatNum, recordTime, InOutValueTypeEnum.fromValue(newDataDetailEntity.getQuoteIdentify()).getEnumValue(), null, recordType);
//            // 更新关联统计
//            nurseStatisticsService.updateNeedResetStatistics(inpatNum, DateUtil.stringToDate(recordTime), InOutValueTypeEnum.fromType(newDataDetailEntity.getQuoteType()).getEnumValue());
            // 绑定引用
            newDataDetailEntity.setQuoteId(statisticsId);
        }

        nurseFileDataDetailMapper.insert(newDataDetailEntity);

        for (int i = 0; i < fileData.getEmrFileDataList().size(); i++) {
            NurseFileData nurseFileData = fileData.getEmrFileDataList().get(i);
            recursiveSave(nurseFileData, fileDataId, inpatNum, recordType, recordTime, newDataDetailEntity.getFileDataDetailId(), i);
        }
    }

    private String getDataValueText(List<NurseFileData> fileDataTemp) {
        StringBuilder sb = new StringBuilder();
        if (CollectionUtils.isNotEmpty(fileDataTemp)) {
            Stack<NurseFileData> stack = new Stack<>();
            for (int i = 0; i < fileDataTemp.size(); i++) {
                NurseFileData topEmrFileData = fileDataTemp.get(i);
                stack.push(topEmrFileData);
                while (!stack.empty()) {
                    NurseFileData nurseFileData = stack.pop();
                    sb.append(nurseFileData.getFileIndexDataEntity().getDataValue());
                    List<NurseFileData> subEmrFileDataList = nurseFileData.getEmrFileDataList();
                    int j = subEmrFileDataList.size();
                    while (--j >= 0) {
                        stack.push(subEmrFileDataList.get(j));
                    }
                }
            }
        }
        return sb.toString();
    }

    /**
     * 编辑保存节点
     *
     * @param fileData
     * @param fileDataId
     * @param inpatNum
     * @param recordTime
     * @param parentId
     * @throws Exception
     */
    private void recursiveEditSave(NurseFileData fileData, String fileDataId, String inpatNum, String recordType, String recordTime, String parentId, Integer sortId) throws Exception {
        // 根据varcode等参数获取当前记录，获取后进行比较更新或者插入操作

        // 无记录，新增
        NurseFileDataDetailEntity newDataDetailEntity = fileData.getFileIndexDataEntity();
        newDataDetailEntity.setFileDataDetailId((newDataDetailEntity.getFileDataDetailId() == null || newDataDetailEntity.getFileDataDetailId().length() != 32) ? UUIDUtil.randomString() : newDataDetailEntity.getFileDataDetailId());
//        newDataDetailEntity.setFileDataDetailId(UUIDUtil.randomString());
        newDataDetailEntity.setDataVersion(newDataDetailEntity.getDataVersion() == null ? 1 : newDataDetailEntity.getDataVersion() + 1);
        newDataDetailEntity.setHospitalId("");
        newDataDetailEntity.setRecordTime(recordTime);
        newDataDetailEntity.setRecordType(recordType);
        newDataDetailEntity.setDataCode(newDataDetailEntity.getDataCode() == null ? "" : newDataDetailEntity.getDataCode());
        newDataDetailEntity.setDataValue(newDataDetailEntity.getDataValue() == null ? "" : newDataDetailEntity.getDataValue());
        newDataDetailEntity.setInpatNum(inpatNum);
        newDataDetailEntity.setElementId(fileData.getElement().getId());
        newDataDetailEntity.setSortId(sortId);
        //判断elementId是否为空，同时校验值域字典
        if (StringUtils.isBlank(newDataDetailEntity.getElementId())) {
            if (StringUtils.isNotBlank(newDataDetailEntity.getDataValue())) {
                String elementId = nurseFileMapper.querySysElementId(StateEnum.MB_WB.getValue());
                if (StringUtils.isBlank(elementId)) {
                    throw new Exception(newDataDetailEntity.getDataValue() + "没有数据元id,无法保存！");
                } else {
                    newDataDetailEntity.setElementId(elementId);
                }
            } else {
                String elementId = nurseFileMapper.querySysElementId(StateEnum.MB_WB.getValue());
                if (StringUtils.isBlank(elementId)) {
                    throw new Exception(newDataDetailEntity.getDataValue() + "没有数据元id,无法保存！");
                } else {
                    newDataDetailEntity.setElementId(elementId);
                }
            }
        }
        newDataDetailEntity.setElementType(fileData.getElement().getType());
        newDataDetailEntity.setFlag("0");
        // TODO: 编辑人编号
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");

        newDataDetailEntity.setOperationId(userId == null ? "创建人ID" : userId);
        newDataDetailEntity.setFileDataId(fileDataId);
        newDataDetailEntity.setParentId(parentId);

//        String varCode = fileData.getElement().getVarCode();
//        if ("shoushumingcheng".equals(varCode)) {
//            Map map = newDataDetailEntity.getExpandFieldsMap();
//            if (map == null) {
//                map = new HashMap();
//            }
//            map.put("varCode", "shoushumingcheng");
//            String expandFields = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty);
//            newDataDetailEntity.setExpandFields(expandFields);
//        }
        // 对于大段无VarCode节点需要将子节点内容冗余进DataValue中，方便后续比较判断数据是否变更
        if (newDataDetailEntity.getVarCode() != null &&
                (newDataDetailEntity.getVarCode().equals("jldccl")
                        || newDataDetailEntity.getVarCode().equals("jlxsecl")
                        || newDataDetailEntity.getVarCode().equals("jlsgsycbz")
                        || newDataDetailEntity.getVarCode().equals("hlbqjhl")
                        || newDataDetailEntity.getVarCode().equals("jlcscla")
                        || newDataDetailEntity.getVarCode().equals("jlxsecl")
                        || newDataDetailEntity.getVarCode().equals("jlsgsycbz"))) {
//            // 转JSON前先清除DataValue，防止多次存储
//            fileData.getFileIndexDataEntity().setDataValue("");
//            // 冗余json
//            String md5 = JSON.toJSONString(fileData.getEmrFileDataList(), SerializerFeature.WriteNullStringAsEmpty);
//            String dataValueMd5 = DigestUtils.md5DigestAsHex(md5.getBytes());
//            newDataDetailEntity.setDataCode(dataValueMd5 == null ? "" : dataValueMd5);

            List<NurseFileData> fileDataTemp = fileData.getEmrFileDataList();
            String dataValueText = this.getDataValueText(fileDataTemp);
            newDataDetailEntity.setDataValue(dataValueText);
        }

        // 护理文书特殊处理出入量统计
        List<String> statisticsTypes = new ArrayList<>(Arrays.asList("4", "5", "6", "7", "8", "9", "10", "11"));
        // 在保存前需要先进行统计标记过滤计算
        if (QuoteTypeEnum.Statistics.getEnumValue().equals(newDataDetailEntity.getQuoteType())) { // 引用属于统计类型
            // 计算统计并将统计id作为引用id保存
            String statisticsId = nurseStatisticsService.inputOutputStatistics(inpatNum, recordTime, InOutValueTypeEnum.fromValue(newDataDetailEntity.getQuoteIdentify()).getEnumValue(), null, recordType);
            // 绑定引用
            newDataDetailEntity.setQuoteId(statisticsId);
        }

        //编辑保存的时，需要重新保存扩展名
        if (newDataDetailEntity.getVarCode() != null && (newDataDetailEntity.getVarCode().equals(StateEnum.HL_RLMC.getValue()) || newDataDetailEntity.getVarCode().equals(StateEnum.HL_XSERLMC.getValue()))) {
            String expandFields = JSON.toJSONString(newDataDetailEntity.getExpandFieldsMap(), SerializerFeature.WriteNullStringAsEmpty);
            newDataDetailEntity.setExpandFields(expandFields);
        }

        nurseFileDataDetailMapper.insert(newDataDetailEntity);
//        // 添加备份
//        nurseFileDataDetailMapper.insertBack(newDataDetailEntity);

        for (int i = 0; i < fileData.getEmrFileDataList().size(); i++) {
            NurseFileData nurseFileData = fileData.getEmrFileDataList().get(i);
            recursiveEditSave(nurseFileData, fileDataId, inpatNum, recordType, recordTime, newDataDetailEntity.getFileDataDetailId(), i);
        }

    }

    /**
     * 获取层级节点
     *
     * @param fileDataId
     * @param parentId
     * @return
     */
    List<NurseFileData> recursiveQueryFileData(String fileDataId, String parentId, String print, boolean transStatistics) {
        List<NurseFileDataDetailEntity> list = new ArrayList<>();
        if (print.equals("0")) {
            list = nurseFileDataDetailMapper.queryDataDetailList(fileDataId, parentId);
        } else {
            list = nurseFileDataDetailMapper.queryPrintDataDetailList(fileDataId, parentId);
        }
        if (ArrayUtils.isNotEmpty(list.toArray())) {
            return convertData(list, transStatistics);
        }
        return new ArrayList<>();
    }

    /**
     * 将模板数据封装为前端需要的节点结构
     *
     * @param tplDetails
     * @return
     */
    private List<NurseFileData> getNurseFileData(List<EmrTemplateDetailEntity> tplDetails, String inpatNum, String recordType) {
        List<NurseFileData> list = new ArrayList<>();
        // 先做无访问库的操作
        for (EmrTemplateDetailEntity tplDetailEntity : tplDetails) {
            NurseFileData nurseFileData = new NurseFileData();
            NurseFileDataDetailEntity entity = new NurseFileDataDetailEntity();
            entity.setBondNo("0");
            entity.setFlag("0");
            entity.setDataValue(tplDetailEntity.getDataValue() == null ? "" : tplDetailEntity.getDataValue());
            entity.setDataCode(tplDetailEntity.getDataCode() == null ? "" : tplDetailEntity.getDataCode());
            entity.setEditIdentification("0");
            entity.setElementId(tplDetailEntity.getElementId());
            entity.setParentId(tplDetailEntity.getParentTplDetailId());
            entity.setTplDetailId(tplDetailEntity.getTplDetailId());
            entity.setShowIdentification(tplDetailEntity.getShowIdentification());
            entity.setDeleteIdentification(tplDetailEntity.getDeleteIdentification());
            entity.setPrintIdentification(tplDetailEntity.getPrintIdentification());
            entity.setRecordType(recordType);
            nurseFileData.setFileIndexDataEntity(entity);
            list.add(nurseFileData);
        }
        Map<String, String> currentUser = getCurrentUser();
        String userName = currentUser.get("userName");
        if (StringUtils.isBlank(userName)) {
            userName = "";
        }
        // 异步执行查库赋值操作
        String finalUserName = userName;
        list.stream().forEach(nurseFileData -> {

            NurseFileDataDetailEntity nurseFileDataDetailEntity = nurseFileData.getFileIndexDataEntity();

            Element element = new Element();
            System.out.println(nurseFileDataDetailEntity.getElementId());
            Element tempElement = nurseFileMapper.queryElementById(nurseFileDataDetailEntity.getElementId());

            if (tempElement != null) {
                element.setId(tempElement.getId());
                element.setName(tempElement.getName());
                element.setType(tempElement.getType());
                element.setMax(tempElement.getMax());
                element.setMin(tempElement.getMin());
                element.setUnit(tempElement.getUnit() == null ? "" : tempElement.getUnit());
                element.setElementPropertyFormat(tempElement.getElementPropertyFormat());
                element.setVarCode(tempElement.getVarCode());
            }

//            String varCode = nurseFileMapper.queryVarCodeByVarValue(nurseFileDataDetailEntity.getElementId());
//
//            element.setVarCode(varCode==null ? "" : varCode);
            nurseFileData.setElement(element);

            nurseFileDataDetailEntity.setVarCode(element.getVarCode());
            nurseFileDataDetailEntity.setElementType(element.getType());
            nurseFileDataDetailEntity.setUnit(element.getUnit() == null ? "" : element.getUnit());
            nurseFileDataDetailEntity.setExpandFieldsMap(new HashMap());
            nurseFileDataDetailEntity.setExpandFields("");

            nurseFileData.setFileIndexDataEntity(nurseFileDataDetailEntity);
            nurseFileData.setEmrFileDataList(new ArrayList<>());
            // 规则过滤
            nurseFileData = ruleFilter(nurseFileData, inpatNum, recordType, finalUserName);
        });
        apgarScoreFirst = true;
        return list;
    }

    /**
     * 构建树结构
     *
     * @param list
     * @param parentDetailId
     * @return
     */
    private List<NurseFileData> buildTreeData(List<NurseFileData> list, String parentDetailId) {
        List<NurseFileData> topList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            NurseFileData node = list.get(i);
//            node.setEmrFileDataList(new ArrayList<>());
            if (node.getFileIndexDataEntity().getParentId() == null || node.getFileIndexDataEntity().getParentId().equals("0")
                    || node.getFileIndexDataEntity().getFileDataDetailId().equals(parentDetailId)) {
                topList.add(node);
                continue;
            }
            for (int j = 0; j < i; j++) {
                NurseFileData parent = list.get(j);
                if (parent.getFileIndexDataEntity().getFileDataDetailId().equals(node.getFileIndexDataEntity().getParentId())) {
                    parent.getEmrFileDataList().add(node);
                    break;
                }
            }
        }
        return topList;
    }

    /**
     * 创建时构建树结构
     *
     * @param list
     * @param parentDetailId
     * @return
     */
    private List<NurseFileData> createBuildTreeData(List<NurseFileData> list, String parentDetailId) {
        List<NurseFileData> topList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            NurseFileData node = list.get(i);
            node.setEmrFileDataList(new ArrayList<>());
            if (node.getFileIndexDataEntity().getParentId() == null
                    || node.getFileIndexDataEntity().getTplDetailId().equals(parentDetailId)) {
                topList.add(node);
                continue;
            }
            for (int j = 0; j < i; j++) {
                NurseFileData parent = list.get(j);
                if (parent.getFileIndexDataEntity().getTplDetailId().equals(node.getFileIndexDataEntity().getParentId())) {
                    parent.getEmrFileDataList().add(node);
                    break;
                }
            }
        }
        return topList;
    }

    private List<NurseFileData> convertData(List<NurseFileDataDetailEntity> list, boolean transStatistics) {
        return list.parallelStream().map(dataEntity -> {
            NurseFileData data = new NurseFileData();

            Element element = new Element();

            Element tempElement = nurseFileMapper.queryElementById(dataEntity.getElementId());
            if (tempElement != null) {
                element.setId(tempElement.getId());
                element.setName(tempElement.getName());
                element.setType(tempElement.getType());
                element.setMax(tempElement.getMax());
                element.setMin(tempElement.getMin());
                element.setUnit(tempElement.getUnit() == null ? "" : tempElement.getUnit());
                element.setElementPropertyFormat(tempElement.getElementPropertyFormat());
            }
            element.setVarCode(dataEntity.getVarCode());
            element.setType(dataEntity.getElementType());
            element.setName(element.getName() == null ? dataEntity.getDataValue() : element.getName());

//                if (dataEntity.getMedicalId()!=null && dataEntity.getMedicalId().equals(dataEntity.getElementId())) {
//                    // 如果医疗术语ID和数据元ID相同，则设置类型为医疗术语
//                    element.setType("20");
//                }
            //redis.set(dataEntity.getElementId(),tempElement);
            data.setElement(element);
            dataEntity.setDataCode(dataEntity.getDataCode() == null ? "" : dataEntity.getDataCode());
            dataEntity.setDataValue(dataEntity.getDataValue() == null ? "" : dataEntity.getDataValue());

            // 如果节点varCode为以下名称，需要将之前设置到dataValue的MD5值清除，否则会影响前端打印显示
            if (dataEntity.getVarCode() != null &&
                    (dataEntity.getVarCode().equals("jldccl")
                            || dataEntity.getVarCode().equals("jlxsecl")
                            || dataEntity.getVarCode().equals("jlsgsycbz")
                            || dataEntity.getVarCode().equals("hlbqjhl")
                            || dataEntity.getVarCode().equals("jlcscla")
                            || dataEntity.getVarCode().equals("jlxsecl")
                            || dataEntity.getVarCode().equals("jlsgsycbz"))) {
                dataEntity.setDataValue("");
            }

            dataEntity.setExpandFieldsMap(JSON.parseObject(dataEntity.getExpandFields() == null ? "{}" : dataEntity.getExpandFields(), Map.class));

            // 添加统计判断 transStatistics 1转换统计，0转换统计
            if (transStatistics && StringUtils.isNotBlank(dataEntity.getQuoteId()) && QuoteTypeEnum.Statistics.getEnumValue().equals(dataEntity.getQuoteType())) {
                NurseStatisticsEntity statisticsEntity = nurseStatisticsMapper.queryOneById(dataEntity.getQuoteId());
                if (statisticsEntity != null) {
                    dataEntity.setDataValue(statisticsEntity.getStatisticsText());
                }
            }

            data.setFileIndexDataEntity(dataEntity);
            data.setEmrFileDataList(new ArrayList<>());
            return data;
        }).collect(Collectors.toList());
    }


    /**
     * 数据元绑定varCode
     *
     * @param map
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result bondVarcode(Map<String, String> map) {
        String elementName = map.get("elementName");
        String varCode = map.get("varCode");
        String varName = map.get("varName");
        // 根据elementName 获取elementId
        String elementId = nurseFileMapper.queryElementIdByElementName(elementName);
        if (elementId == null) {
            return ResultGenerator.genFailedResult("当前数据元不存在");
        }
        if (varCode == null || varCode.equals("") || varName == null || varName.equals("")) {
            return ResultGenerator.genFailedResult("varCode或varName不能为空");
        }

        String hasVarCode = nurseFileMapper.queryVarCodeByVarValue(elementId);
        if (hasVarCode != null) {
            return ResultGenerator.genFailedResult("当前数据元已经拥有varCode" + hasVarCode);
        }

        String hasElementName = nurseFileMapper.queryElementNameByVarCode(varCode);
        if (hasElementName != null) {
            return ResultGenerator.genFailedResult("当前varCode已经绑定数据元" + hasElementName);
        }

        nurseFileMapper.bondElementWithVarCode(varCode, varName, elementId);

        return ResultGenerator.genOkResult("绑定成功");
    }


    /**
     * 获取当前用户信息
     *
     * @return
     */
    public Map<String, String> getCurrentUser() {

        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        Map<String, String> currentUser = nurseFileMapper.getUser(userId);
        if (currentUser == null)
            return new HashMap<String, String>();
        return currentUser;

    }

    /**
     * 获取指定住院号的apgar评分
     *
     * @param inpatNum
     * @return
     */
    @Override
    public Result getApgarScore(String inpatNum) {
        Map<String, String> scoreMap = new HashMap<>();

        NurseFileDataEntity nurseFileDataEntity = nurseFileDataMapper.queryOnlyRecord(NurseFileTypeEnum.ApgarScore.getEnumValue(), inpatNum);
        if (nurseFileDataEntity != null) {
            String apgaryf = nurseFileDataDetailMapper.queryApgarAccess("ck_jlapgaryf", nurseFileDataEntity.getFileDataId());
            String apgarwf = nurseFileDataDetailMapper.queryApgarAccess("ck_jlapgarwf", nurseFileDataEntity.getFileDataId());
            String apgarsf = nurseFileDataDetailMapper.queryApgarAccess("ck_jlapgarsf", nurseFileDataEntity.getFileDataId());

            scoreMap.put("apgaryf", apgaryf == null ? "" : apgaryf);
            scoreMap.put("apgarwf", apgarwf == null ? "" : apgarwf);
            scoreMap.put("apgarsf", apgarsf == null ? "" : apgarsf);
            scoreMap.put("fileDataId", nurseFileDataEntity.getFileDataId());
        } else {
            scoreMap.put("apgaryf", "");
            scoreMap.put("apgarwf", "");
            scoreMap.put("apgarsf", "");
            scoreMap.put("fileDataId", "");
        }

        return ResultGenerator.genOkResult(scoreMap);
    }


    @Override
    public Result isSummary(Map<String, String> map) {
        Map result = nurseFileDataMapper.isSummary(map);
        if (result == null) {
            return ResultGenerator.genOkResult();
        } else {
            return ResultGenerator.genOkResult("是否更新出入量总结");
        }
    }

    /**
     * 创建出入量统计记录
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result createInputOutputSummary(Map<String, String> map) {

        String inpatNum = map.get("inpatNum"); // 住院编号
//        String inpatNum = "1081273-1";
        String recordTime = map.get("recordTime"); // 总结日（方便后期扩展可以选择总结那一天的出入量总结）
        String fileIndexId = map.get("fileIndexId"); // 用于绑定记录到指定患者护理文书上
        String recordType = map.get("recordType"); // 记录类型
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (recordTime.length() == 10) {
            recordTime += " 07:00";
        }

        Date date = new Date();
        try {
            date = sdf.parse(recordTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        cal.set(Calendar.HOUR_OF_DAY, 7);//控制时
        cal.set(Calendar.MINUTE, 0);//控制分
        cal.set(Calendar.SECOND, 0);//控制秒
        Date today7Clock = cal.getTime();

        recordTime = sdf.format(today7Clock); // 目前将总结日设置为固定每天7点整，后续可能需要可以手动调整总结日

        NurseFileDataEntity oldNurseFileDataEntity = nurseFileDataMapper.querySameTimeRecord(recordType, inpatNum, recordTime, "1");

        if (oldNurseFileDataEntity == null) {
            // 新增统计，新增列表记录
            String statisticsId = nurseStatisticsService.inputOutputSummary(inpatNum, today7Clock, null);
            if (statisticsId == null) {
                return ResultGenerator.genOkResult("当前患者无出入量总结类型医嘱");
            }
            String tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbhljl");
            NurseFileDataEntity fileDataEntity = new NurseFileDataEntity();
            fileDataEntity.setFileDataId(UUIDUtil.randomString());
            fileDataEntity.setDataVersion(1);
            fileDataEntity.setFlag("0");
            fileDataEntity.setTplId(tplId);
            fileDataEntity.setHospitalId("");
            fileDataEntity.setFileIndexId(fileIndexId);
            fileDataEntity.setInpatNum(inpatNum);
            fileDataEntity.setRecordTime(recordTime);
            // 设置统计相关绑定
            fileDataEntity.setCareType("1");
            fileDataEntity.setStatisticsId(statisticsId);

            // TODO: 创建人编号应该从请求头中获取
            String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");

            fileDataEntity.setOperationId(userId == null ? "创建人ID" : userId);
            fileDataEntity.setRecordType(recordType);

            nurseFileDataMapper.insert(fileDataEntity);

            // 获取需要更新的统计记录，更新（起始时间小于新增记录的截止时间的记录）
            nurseStatisticsService.updateNeedResetStatistics(inpatNum, today7Clock, InOutValueTypeEnum.IN_OUT_SUMMARY.getEnumValue(), recordType);


        } else {
            // 删除列表记录，删除统计
            nurseFileDataMapper.deleteDataRecordAndStatistics(oldNurseFileDataEntity.getFileDataId(), oldNurseFileDataEntity.getStatisticsId());
            // 新增统计，新增列表记录
            String statisticsId = nurseStatisticsService.inputOutputSummary(inpatNum, today7Clock, null);
            if (statisticsId == null) {
                return ResultGenerator.genOkResult("当前患者无出入量总结类型医嘱");
            }
            String tplId = nurseFileMapper.queryTplIdByVarCode("ck_mbhljl");
            NurseFileDataEntity fileDataEntity = new NurseFileDataEntity();
            fileDataEntity.setFileDataId(UUIDUtil.randomString());
            fileDataEntity.setDataVersion(1);
            fileDataEntity.setFlag("0");
            fileDataEntity.setTplId(tplId);
            fileDataEntity.setHospitalId("");
            fileDataEntity.setFileIndexId(fileIndexId);
            fileDataEntity.setInpatNum(inpatNum);
            fileDataEntity.setRecordTime(recordTime);
            // 设置统计相关绑定
            fileDataEntity.setCareType("1");
            fileDataEntity.setStatisticsId(statisticsId);
            //新增记录时不需要覆盖统计记录的签名
            if (map.get("changeSign") != null && "0".equals(map.get("changeSign"))) {
                fileDataEntity.setOperationId(oldNurseFileDataEntity.getOperationId());
            } else {
                String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
                fileDataEntity.setOperationId(userId == null ? "创建人ID" : userId);
            }
            fileDataEntity.setRecordType(recordType);
            nurseFileDataMapper.insert(fileDataEntity);
        }

        /*if(StringUtils.isNotBlank(recordTime)){
            if(recordTime.length()>10){
                recordTime=recordTime.substring(0,10);
            }
            String prevTime = DateUtil.dateToString(DateUtil.getDateBefore(DateUtil.stringToDate(recordTime+" 00:00:00","yyyy-MM-dd HH:mm:ss"),1),"yyyy-MM-dd");

            this.computeSummary(inpatNum,prevTime);
        }*/

        return ResultGenerator.genOkResult("创建成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteSummaryRecord(Map<String, String> map) {
        String fileDataId = map.get("fileDataId");
        if (fileDataId == null) {
            return ResultGenerator.genOkResult("记录号不能为空");
        }
        NurseFileDataEntity oldNurseFileDataEntity = nurseFileDataMapper.queryOneDataRecord(fileDataId);
        if (oldNurseFileDataEntity == null) {
            return ResultGenerator.genOkResult("当前记录不存在");
        }

        // 获取当前要删除出入量总结记录上一条记录用于删除完成后进行更新
        NurseStatisticsEntity nurseStatisticsEntity = nurseStatisticsMapper.queryOneById(oldNurseFileDataEntity.getStatisticsId());

        // 删除列表记录，删除统计
//        nurseFileDataMapper.deleteDataRecordAndStatistics(oldNurseFileDataEntity.getFileDataId(), oldNurseFileDataEntity.getStatisticsId());
        nurseFileDataMapper.deleteStaticsDetail(oldNurseFileDataEntity.getStatisticsId());
        nurseFileDataMapper.deleteStatics(oldNurseFileDataEntity.getStatisticsId());
        nurseFileDataMapper.deleteDataRecord(oldNurseFileDataEntity.getFileDataId());
        // TODO: 需要更新之后最近一条出入量总结统计记录
        if (nurseStatisticsEntity != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date nodeDate = null;
            try {
                nodeDate = sdf.parse(nurseStatisticsEntity.getEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            nurseStatisticsService.updateNeedResetStatistics(nurseStatisticsEntity.getInpatNum(), nodeDate, nurseStatisticsEntity.getStatisticsType(), oldNurseFileDataEntity.getRecordType());
        }

        return ResultGenerator.genOkResult("删除成功");
    }


    /**
     *
     * @param inpatNum 76615-1
     * @param day  yyyy-MM-dd
     */
    private void computeSummary(String inpatNum, String day) {
        //出入量带入的时间 15号的体温单带入  16号7点的出入量总计
        //尿量带入时间为   当天    15号带入  15号护理文书中的24小时尿量总计
        String inOutTotalSummary = patientTemperatureMapper.queryNurseStatistics(inpatNum, DateUtil.dateToString(DateUtil.getDateAfter(DateUtil.stringToDate(day), 1), "yyyy-MM-dd"), "0");
        if (org.apache.commons.lang.StringUtils.isNotBlank(inOutTotalSummary) && inOutTotalSummary.split("-").length == 12) {
            if ("24".equals(inOutTotalSummary.split("-")[0])) {
                patientTemperatureMapper.saveInAndOut(inpatNum, day, inOutTotalSummary.split("-")[6], inOutTotalSummary.split("-")[11]);
            } else {
                patientTemperatureMapper.saveInAndOut(inpatNum, day, inOutTotalSummary.split("-")[6] + "(" + inOutTotalSummary.split("-")[0] + "h)", inOutTotalSummary.split("-")[11] + "(" + inOutTotalSummary.split("-")[0] + "h)");
            }
        } else {
            patientTemperatureMapper.saveInAndOut(inpatNum, day, "", "");
        }
        //24h尿量
        String urineVolume = patientTemperatureMapper.queryNurseStatistics(inpatNum, day, "6");
        if (org.apache.commons.lang.StringUtils.isNotBlank(urineVolume)) {
            String urineStr = urineVolume.substring(urineVolume.indexOf("小时尿量") + 4, urineVolume.indexOf("ml"));
            //当前时间如果有导尿医嘱 尿量后需要加/C
            String isHasC = patientTemperatureMapper.queryisHasC(inpatNum, day);
            if (org.apache.commons.lang.StringUtils.isNotBlank(isHasC)) {
                urineStr = urineStr + "/C";
            }
            if ("24".equals(urineVolume.substring(0, 2))) {
                patientTemperatureMapper.saveUrineVolume(inpatNum, day, urineStr);
            } else {
                patientTemperatureMapper.saveUrineVolume(inpatNum, day, urineStr + "(" + urineVolume.substring(0, urineVolume.indexOf("小时尿量")) + "h)");
            }
        } else {
            patientTemperatureMapper.saveUrineVolume(inpatNum, day, "");
        }
    }

    @Override
    public Result sign(String loginName, String userPwd, String fileDataId) {
        Map<String, String> sysUser = nurseFileMapper.getSysUser(loginName);
        if (sysUser == null || sysUser.isEmpty()) {
            return ResultGenerator.genFailedResult("用户不存在。");
        }
        String inputPwd = passwordEncoder.encode(userPwd);
        if (!passwordEncoder.matches(userPwd, sysUser.remove("userPwd"))) {
            return ResultGenerator.genFailedResult("密码错误。");
        }
        //产二和中期前台判断 不传dataId
        if (StringUtils.isNotBlank(fileDataId)) {
            String userId = "";
            NurseFileDataEntity entity = nurseFileDataMapper.queryOneDataRecord(fileDataId);
            if (entity == null) {
                userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                        .getHeader("zuul_id");
            } else {
                userId = entity.getOperationId();
            }
            if (userId.equals(sysUser.get("userId"))) {
                return ResultGenerator.genFailedResult("不能重复签名");
            }
        }
        return ResultGenerator.genOkResult(sysUser);
    }

    @Override
    public Result getTplDetail(String tplDetailId, String inpatNum, String recordType) {
        List<EmrTemplateDetailEntity> tplDetails = nurseFileMapper.queryTplDetailByTplDetailId(tplDetailId);
        List list = getNurseFileData(tplDetails, inpatNum, recordType);
        List<NurseFileData> fileDatalist = createBuildTreeData(list, tplDetailId);
        return ResultGenerator.genOkResult(fileDatalist);
    }


    @Override
    public Result getRule(String inpatNum, String recordTime, String recordType, String varCode) {

        if (NurseFileTypeEnum.Care.getEnumValue().equals(recordType)) {
            if (varCode.equals("hlrlmc") || varCode.equals("hlclmc")) {
                // 获取患者自定义备注下拉
                return ResultGenerator.genOkResult();
            }
        } else if (NurseFileTypeEnum.Wait.getEnumValue().equals(recordType)) {

        } else if (NurseFileTypeEnum.LabourA.getEnumValue().equals(recordType)) {

        } else if (NurseFileTypeEnum.LabourB.getEnumValue().equals(recordType)) {

        } else if (NurseFileTypeEnum.Neonatus.getEnumValue().equals(recordType)) {

        } else if (NurseFileTypeEnum.Oxytocin.getEnumValue().equals(recordType)) {
            if (varCode.equals("ck_mbsgsycjl")) {
                if (StringUtils.isBlank(recordTime)) {
                    recordTime = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm");
                }
                // 获取最近一次记录，如果没有记录则返回系统当前时间
                NurseFileDataEntity nurseFileDataEntity = nurseFileDataMapper.queryLastData(inpatNum, recordTime, recordType);
                if (nurseFileDataEntity != null) {
                    Date date = DateUtil.getTargetDate(DateUtil.stringToDate(nurseFileDataEntity.getRecordTime()), 0, 0, 0, 0, 15, 0);
                    if (date.getTime() <= new Date().getTime()) {
                        return ResultGenerator.genOkResult(DateUtil.dateToString(date, "yyyy-MM-dd HH:mm"));
                    }
                }

                return ResultGenerator.genOkResult(recordTime);

            }

        } else if (NurseFileTypeEnum.Induction.getEnumValue().equals(recordType)) {


        } else {

        }

        return null;
    }

    boolean apgarScoreFirst = true;//Apgar第一次评分只赋值第一个时间

    /**
     * 规则过滤
     *
     * @param nurseFileData
     * @param inpatNum
     * @param recordType
     * @return
     */
    public NurseFileData ruleFilter(NurseFileData nurseFileData, String inpatNum, String recordType, String userName) {

        NurseFileDataDetailEntity detailEntity = nurseFileData.getFileIndexDataEntity();

        if (StringUtils.isNotBlank(detailEntity.getDataValue()) || StringUtils.isBlank(detailEntity.getVarCode())) {
            // 有默认值则直接返回
            return nurseFileData;
        }

        if (NurseFileTypeEnum.Care.getEnumValue().equals(recordType)) {
            // 添加默认签名
            if (detailEntity.getVarCode() != null && detailEntity.getVarCode().equals("ck_jlhsqm")) {
                detailEntity.setDataValue(userName);
            }

            // 添加默认单位
            if (detailEntity.getVarCode() != null && (detailEntity.getVarCode().equals("hlclz") || detailEntity.getVarCode().equals("hlrlz"))) {
                detailEntity.setUnit("ml");
            }


        } else if (NurseFileTypeEnum.Wait.getEnumValue().equals(recordType)) {

            // 添加默认签名
            if (detailEntity.getVarCode() != null && detailEntity.getVarCode().equals("jldcqm")) {
                detailEntity.setDataValue(userName);
            }

        } else if (NurseFileTypeEnum.LabourA.getEnumValue().equals(recordType)) {

            // 添加默认签名
            if (detailEntity.getVarCode() != null && detailEntity.getVarCode().equals("jlcsqma")) {
                detailEntity.setDataValue(userName);
            }

        } else if (NurseFileTypeEnum.LabourB.getEnumValue().equals(recordType)) {

            // 若待产记录中，宫缩情况数据中首次数值=（30"/5-6'）时，将该条数据的记录时间带入 宫缩开始时间
            if (detailEntity.getVarCode().equals("ck_jlgskssj")) {
                // 获取第一次宫缩时间
                String firstContractionTime = nurseFileDataDetailMapper.queryFirstContractionTime(inpatNum);
                if (StringUtils.isNotBlank(firstContractionTime)) {
                    detailEntity.setDataValue(firstContractionTime);
                }
                return nurseFileData;
            }

            // 若待产记录中最后一条数据中，处理及签名中包含【宫口开全】时；则将该数据记录时间带入。
            if (detailEntity.getVarCode().equals("ck_jlgkkqsj")) {
                // 宫口开全时间
                String ostiumOfUterusOpenTime = nurseFileDataDetailMapper.queryOstiumOfUterusOpenTime(inpatNum);
                if (StringUtils.isNotBlank(ostiumOfUterusOpenTime)) {
                    detailEntity.setDataValue(ostiumOfUterusOpenTime);
                }
                return nurseFileData;
            }

            // 查询待产记录中处理及签名中包含【胎膜自破】或【人工破膜】时，将该条数据的记录时间带入；
            if (detailEntity.getVarCode().equals("ck_jlpmsj")) {
                // 破膜时间
                String outMembranaTime = nurseFileDataDetailMapper.queryOutMembranaTime(inpatNum);
                if (StringUtils.isNotBlank(outMembranaTime)) {
                    detailEntity.setDataValue(outMembranaTime);
                }
                return nurseFileData;
            }

            // 起始时间：同步母婴同室第一条记录；结束时间为开始时间后半个小时
            if (detailEntity.getVarCode().equals("ck_jlzjczsxq")) {
                // 母婴早接触、早吮吸时间
                String[] inpats = inpatNum.split("-");
                if (inpats != null && inpats.length > 0) {
                    String earlyContactTime = nurseFileDataDetailMapper.queryEarlyContactTime(inpats[0]);
                    if (StringUtils.isNotBlank(earlyContactTime)) {
                        detailEntity.setDataValue(earlyContactTime);
                    }
                }
                return nurseFileData;
            }
            //胎儿娩出时间
            if ("ck_jltewcsj".equals(detailEntity.getVarCode())) {
                detailEntity.setDataValue(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm"));
                return nurseFileData;
            }
            // 起始时间：同步母婴同室第一条记录；结束时间为开始时间后半个小时
            if (detailEntity.getVarCode().equals("ck_jlzjczsxz")) {
                // 母婴早接触、早吮吸时间
                String[] inpats = inpatNum.split("-");
                if (inpats != null && inpats.length > 0) {
                    String earlyContactTime = nurseFileDataDetailMapper.queryEarlyContactTime(inpats[0]);
                    if (StringUtils.isNotBlank(earlyContactTime)) {
                        Long time = DateUtil.stringToTimestamp(earlyContactTime).getTime() + 30 * 1000 * 60;
                        Date date = new Date(time);
                        Date currDate = new Date();
                        if (date.getTime() > (currDate.getTime())) {
                            detailEntity.setDataValue(DateUtil.dateToString(currDate, "yyyy-MM-dd HH:mm"));
                        } else {
                            detailEntity.setDataValue(DateUtil.dateToString(date, "yyyy-MM-dd HH:mm"));
                        }
                    }
                }
                return nurseFileData;
            }

        } else if (NurseFileTypeEnum.Neonatus.getEnumValue().equals(recordType)) {

            // 添加默认签名
            if (detailEntity.getVarCode() != null && detailEntity.getVarCode().equals("jlxseqm")) {
                detailEntity.setDataValue(userName);
            }

        } else if (NurseFileTypeEnum.Oxytocin.getEnumValue().equals(recordType)) {

            // 添加默认签名
            if (detailEntity.getVarCode() != null && detailEntity.getVarCode().equals("jlsgsqm")) {
                detailEntity.setDataValue(userName);
            }

            if (detailEntity.getVarCode().equals("jlsgsds")) {

                // 先获取指定时刻前的最近一条指定类型记录
                String recordTime = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm");
                if (detailEntity.getRecordTime() != null)
                    recordTime = detailEntity.getRecordTime();
                NurseFileDataEntity nurseFileDataEntity = nurseFileDataMapper.queryLastData(inpatNum, recordTime, recordType);
                if (nurseFileDataEntity != null) {
                    NurseFileDataDetailEntity fileDataDetailEntity = nurseFileDataDetailMapper.queryOneDataDetail(nurseFileDataEntity.getFileDataId(), detailEntity.getVarCode());
                    if (fileDataDetailEntity != null && fileDataDetailEntity.getDataValue() != null) {
                        detailEntity.setDataValue(String.valueOf(Integer.parseInt(fileDataDetailEntity.getDataValue()) + 4));
                    }
                } else {
                    // 未找到上次记录，返回默认值 8
                    nurseFileData.getFileIndexDataEntity().setDataValue("8");
                }
            }
            return nurseFileData;

        } else if (NurseFileTypeEnum.Induction.getEnumValue().equals(recordType)) {
            if ("ck_jlpmsj".equals(detailEntity.getVarCode())) {
                // 破膜时间
                String outMembranaTime = nurseFileDataDetailMapper.queryOutMembranaTime(inpatNum);
                if (StringUtils.isNotBlank(outMembranaTime)) {
                    detailEntity.setDataValue(outMembranaTime);
                } else {
                    detailEntity.setDataValue(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm"));
                }
                return nurseFileData;
            }
            if ("ck_jltpwcsj".equals(detailEntity.getVarCode()) || "ck_jltewcsj".equals(detailEntity.getVarCode())) {
                detailEntity.setDataValue(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm"));
                return nurseFileData;
            }

        } else if (NurseFileTypeEnum.LabourBwatch.getEnumValue().equals(recordType)) {
            // 产二产后观察返回系统当前时间作为默认时间
            if (detailEntity.getVarCode() != null && detailEntity.getVarCode().equals("ck_jlchgcsj")) {
                detailEntity.setDataValue(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm"));
            }
        } else if (NurseFileTypeEnum.InductionWatch.getEnumValue().equals(recordType)) {
            // 中期产后观察返回系统当前时间作为默认时间
            if (detailEntity.getVarCode() != null && detailEntity.getVarCode().equals("ck_jlchgcsj")) {
                detailEntity.setDataValue(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm"));
            }
        } else if (NurseFileTypeEnum.InductionWait.getEnumValue().equals(recordType)) {
            // 添加默认签名
            if (detailEntity.getVarCode() != null && detailEntity.getVarCode().equals("jldcqm")) {
                detailEntity.setDataValue(userName);
            }
        } else if (NurseFileTypeEnum.ApgarScore.getEnumValue().equals(recordType)) {

            // 添加默认签名
            if (detailEntity.getVarCode() != null && detailEntity.getVarCode().equals("ck_jlpfqm")) {
                detailEntity.setDataValue(userName);
            }
//            NursePatientMsgDTO dto = nursePatientMapper.getPatientInfo(inpatNum);
//            if (dto!=null && StringUtils.isNotBlank(dto.getBirthDay())) {
//                if ("ck_jlpfsj".equals(detailEntity.getVarCode()) && apgarScoreFirst) {
//                    try {
//                        Date date = DateUtil.stringToDate(dto.getBirthDay());
//                        Calendar calendar = Calendar.getInstance();
//                        calendar.setTime(date);
//                        calendar.add(Calendar.MINUTE, 1);
//                        detailEntity.setDataValue(DateUtil.dateToString(calendar.getTime(),"yyyy-MM-dd HH:mm"));
//                        apgarScoreFirst = false;
//                    } catch (Exception e) {
//                        logger.error("转换婴儿出生日期+1min失败", e);
//                    }
//                }
//            }
        } else if (NurseFileTypeEnum.PediatricGeneralCareRecord.getEnumValue().equals(recordType)) {

            // 添加默认签名
            if (detailEntity.getVarCode() != null && detailEntity.getVarCode().equals("ck_jlhsqm")) {
                detailEntity.setDataValue(userName);
            }
        } else if (NurseFileTypeEnum.NewbornCareRecord.getEnumValue().equals(recordType)) {

            // 添加默认签名
            if (detailEntity.getVarCode() != null && detailEntity.getVarCode().equals("ck_jlhsqm")) {
                detailEntity.setDataValue(userName);
            }
        } else {

        }

        return nurseFileData;
    }


    @Override
    public Result getFileIndexId(String inpatNum, String recordType) {
        String fileIndexId = nurseFileIndexMapper.queryFileIndexIdByInpatNum(inpatNum, recordType);
        return ResultGenerator.genOkResult(fileIndexId);
    }


    @Override
    public Result getAllRemarks(String fileIndexId, Integer type) {
        Map map = new HashMap();

        if (type == 1) { // 护理记录单
            // 获取意识基础数据元selections
            List<Map<String, String>> consciousList = nurseFileMapper.queryConsciousElementSelections();

            // 获取出量名称基础数据元selections
            List<Map<String, String>> outputList = nurseFileMapper.queryOutputElementSelections();

            // 获取评估项目基础数据元selections
            List<Map<String, String>> estimateList = nurseFileMapper.queryEstimateElementSelections();

            if (fileIndexId != null) {
                // 1获取NURSE_FILE_INDEX中记录的NURSE_CUSTOMIZE_EXPAND获取出量名称和项目名称的扩展记录
                String recordJson = nurseFileMapper.queryExtends(fileIndexId);
                if (recordJson != null) {
                    Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);
                    // 出量管道
                    List<Map<String, String>> pipeList = map1.get("pipe");
                    if (pipeList != null) {
                        Integer optionsSrcCount = outputList.size();
                        // 依次取出插入的名称拼接返回
                        for (int i = 0; i < pipeList.size(); i++) {
                            Map<String, String> map3 = pipeList.get(i);
                            String currName = map3.get("name");
                            String numStr = longNumStr.substring(optionsSrcCount + i, optionsSrcCount + i + 1);
                            String fullName = numStr + currName;
                            Map<String, String> map2 = new HashMap<>();

                            map2.put("dataText", fullName);
                            map2.put("id", map3.get("del"));
                            map2.put("dataValue", "");
                            outputList.add(map2);
                        }

                    }
                    // 评估项目
                    List<Map<String, String>> assessList = map1.get("assess");
                    if (assessList != null) {
                        Integer optionsSrcCount = estimateList.size();
                        // 依次取出插入的名称拼接返回
                        for (int i = 0; i < assessList.size(); i++) {
                            Map<String, String> map3 = assessList.get(i);
                            String currName = map3.get("name");
                            String numStr = longNumStr.substring(optionsSrcCount + i, optionsSrcCount + i + 1);
                            String fullName = numStr + currName;
                            Map<String, String> map2 = new HashMap<>();
                            map2.put("dataText", fullName);
                            map2.put("id", map3.get("del"));
                            map2.put("dataValue", "");
                            estimateList.add(map2);
                        }
                    }
                    //意识
                    List<Map<String, String>> realizeList = map1.get("realize");
                    if (realizeList != null) {
                        Integer optionsSrcCount = consciousList.size();
                        // 依次取出插入的名称拼接返回
                        for (int i = 0; i < realizeList.size(); i++) {
                            Map<String, String> map3 = realizeList.get(i);
                            String currName = map3.get("name");
                            String numStr = longNumStr.substring(optionsSrcCount + i, optionsSrcCount + i + 1);
                            String fullName = numStr + currName;
                            Map<String, String> map2 = new HashMap<>();
                            map2.put("dataText", fullName);
                            map2.put("id", map3.get("del"));
                            map2.put("dataValue", "");
                            consciousList.add(map2);
                        }
                    }


                }
            }

            Result pipResult = getOtherPipes3(RemarkTypeEnum.IN_OUT_PIPES.getEnumValue(), fileIndexId, 1);
            List<Map<String, String>> list = (List<Map<String, String>>) pipResult.getData();

            for (Map<String, String> allItem : list) {
                for (Map<String, String> item : outputList) {
                    String itemStr = item.get("dataText").substring(1, item.get("dataText").length());
                    if (allItem.get("dataText").equals(itemStr)) {
                        item.put("dataValue", allItem.get("dataValue"));
                        item.put("dataId", allItem.get("id"));
                    }
                }
            }

            map.put("conscious", consciousList);
            map.put("output", outputList);
            map.put("estimate", estimateList);
            return ResultGenerator.genOkResult(map);
        } else if (type == 2) { // 新生儿护理记录单
            // 获取精神
            List<Map<String, String>> mindList = nurseFileMapper.queryCommonDictionryValues("ck_jljszd");

            // 获取吸氧方式
            List<Map<String, String>> oxygenList = nurseFileMapper.queryCommonDictionryValues("ck_jlxyfszd");

            // 获取导管
            List<Map<String, String>> pipesList = nurseFileMapper.queryCommonDictionryValues("ck_jlxsedgzd");

            // 获取评估项目
            List<Map<String, String>> assessmentList = nurseFileMapper.queryCommonDictionryValues("ck_jlxsepgxmzd");

            if (fileIndexId != null) {
                // 1获取NURSE_FILE_INDEX中记录的NURSE_CUSTOMIZE_EXPAND获取出量名称和项目名称的扩展记录
                String recordJson = nurseFileMapper.queryExtends(fileIndexId);
                if (recordJson != null) {
                    Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);
                    // 精神
                    List<Map<String, String>> expandMindList = map1.get("mind");
                    if (expandMindList != null) {
                        Integer optionsSrcCount = mindList.size();
                        // 依次取出精神的名称拼接返回
                        for (int i = 0; i < expandMindList.size(); i++) {
                            Map<String, String> map3 = expandMindList.get(i);
                            String currName = map3.get("name");
                            String numStr = longNumStr.substring(optionsSrcCount + i, optionsSrcCount + i + 1);
                            String fullName = numStr + currName;
                            Map<String, String> map2 = new HashMap<>();

                            map2.put("dataText", fullName);
                            map2.put("id", map3.get("del"));
                            map2.put("dataValue", "");
                            mindList.add(map2);
                        }

                    }

                    // 吸氧方式
                    List<Map<String, String>> expandOxygenList = map1.get("oxygen");
                    if (expandOxygenList != null) {
                        Integer optionsSrcCount = oxygenList.size();
                        // 依次取出精神的名称拼接返回
                        for (int i = 0; i < expandOxygenList.size(); i++) {
                            Map<String, String> map3 = expandOxygenList.get(i);
                            String currName = map3.get("name");
                            String numStr = longNumStr.substring(optionsSrcCount + i, optionsSrcCount + i + 1);
                            String fullName = numStr + currName;
                            Map<String, String> map2 = new HashMap<>();

                            map2.put("dataText", fullName);
                            map2.put("id", map3.get("del"));
                            map2.put("dataValue", "");
                            oxygenList.add(map2);
                        }

                    }

                    // 导管
                    List<Map<String, String>> expandPipesList = map1.get("newpipe");
                    if (expandPipesList != null) {
                        Integer optionsSrcCount = pipesList.size();
                        // 依次取出精神的名称拼接返回
                        for (int i = 0; i < expandPipesList.size(); i++) {
                            Map<String, String> map3 = expandPipesList.get(i);
                            String currName = map3.get("name");
                            String numStr = longNumStr.substring(optionsSrcCount + i, optionsSrcCount + i + 1);
                            String fullName = numStr + currName;
                            Map<String, String> map2 = new HashMap<>();

                            map2.put("dataText", fullName);
                            map2.put("id", map3.get("del"));
                            map2.put("dataValue", "");
                            pipesList.add(map2);
                        }

                    }

                    // 评估项目
                    List<Map<String, String>> expandAssessmentList = map1.get("newassess");
                    if (expandAssessmentList != null) {
                        Integer optionsSrcCount = assessmentList.size();
                        // 依次取出精神的名称拼接返回
                        for (int i = 0; i < expandAssessmentList.size(); i++) {
                            Map<String, String> map3 = expandAssessmentList.get(i);
                            String currName = map3.get("name");
                            String numStr = longNumStr.substring(optionsSrcCount + i, optionsSrcCount + i + 1);
                            String fullName = numStr + currName;
                            Map<String, String> map2 = new HashMap<>();

                            map2.put("dataText", fullName);
                            map2.put("id", map3.get("del"));
                            map2.put("dataValue", "");
                            assessmentList.add(map2);
                        }

                    }
                }
            }

            map.put("mind", mindList);
            map.put("oxygen", oxygenList);
            map.put("newpipe", pipesList);
            map.put("newassess", assessmentList);
            return ResultGenerator.genOkResult(map);
        } else if (type == 3) { // 儿科护理记录单
            // 获取意识基础数据元selections
            List<Map<String, String>> consciousList = nurseFileMapper.queryConsciousElementSelections();

            // 获取导管
            List<Map<String, String>> pipesList = nurseFileMapper.queryCommonDictionryValues("ck_jlxsedgzd");

            // 获取评估项目
            List<Map<String, String>> assessmentList = nurseFileMapper.queryCommonDictionryValues("ck_jlekpgmczd");

            if (fileIndexId != null) {
                // 1获取NURSE_FILE_INDEX中记录的NURSE_CUSTOMIZE_EXPAND获取出量名称和项目名称的扩展记录
                String recordJson = nurseFileMapper.queryExtends(fileIndexId);
                if (recordJson != null) {
                    Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);
                    //意识
                    List<Map<String, String>> realizeList = map1.get("realize");
                    if (realizeList != null) {
                        Integer optionsSrcCount = consciousList.size();
                        // 依次取出插入的名称拼接返回
                        for (int i = 0; i < realizeList.size(); i++) {
                            Map<String, String> map3 = realizeList.get(i);
                            String currName = map3.get("name");
                            String numStr = longNumStr.substring(optionsSrcCount + i, optionsSrcCount + i + 1);
                            String fullName = numStr + currName;
                            Map<String, String> map2 = new HashMap<>();
                            map2.put("dataText", fullName);
                            map2.put("id", map3.get("del"));
                            map2.put("dataValue", "");
                            consciousList.add(map2);
                        }
                    }


                    // 导管
                    List<Map<String, String>> expandPipesList = map1.get("newpipe");
                    if (expandPipesList != null) {
                        Integer optionsSrcCount = pipesList.size();
                        // 依次取出精神的名称拼接返回
                        for (int i = 0; i < expandPipesList.size(); i++) {
                            Map<String, String> map3 = expandPipesList.get(i);
                            String currName = map3.get("name");
                            String numStr = longNumStr.substring(optionsSrcCount + i, optionsSrcCount + i + 1);
                            String fullName = numStr + currName;
                            Map<String, String> map2 = new HashMap<>();

                            map2.put("dataText", fullName);
                            map2.put("id", map3.get("del"));
                            map2.put("dataValue", "");
                            pipesList.add(map2);
                        }

                    }

                    // 评估项目
                    List<Map<String, String>> expandAssessmentList = map1.get("childassess");
                    if (expandAssessmentList != null) {
                        Integer optionsSrcCount = assessmentList.size();
                        // 依次取出精神的名称拼接返回
                        for (int i = 0; i < expandAssessmentList.size(); i++) {
                            Map<String, String> map3 = expandAssessmentList.get(i);
                            String currName = map3.get("name");
                            String numStr = longNumStr.substring(optionsSrcCount + i, optionsSrcCount + i + 1);
                            String fullName = numStr + currName;
                            Map<String, String> map2 = new HashMap<>();

                            map2.put("dataText", fullName);
                            map2.put("id", map3.get("del"));
                            map2.put("dataValue", "");
                            assessmentList.add(map2);
                        }

                    }
                }
            }

            map.put("conscious", consciousList);
            map.put("newpipe", pipesList);
            map.put("childassess", assessmentList);
            return ResultGenerator.genOkResult(map);
        } else {
            return ResultGenerator.genFailedResult("未定义类型");
        }
    }

    public Result getOtherPipes3(String type, String fileIndexId, int isAll) {//0否 1 是
        Map<String, Object> data = new HashMap<>();
        if (type.equals(RemarkTypeEnum.IN_OUT_PIPES.getEnumValue())) { // type=1 导管，type=2 评估项目

            // 获取出量名称基础数据元selections
            List<Map<String, String>> outputList = nurseFileMapper.queryOutputElementSelections();
            // 获取当前患者自定义导管扩展，填入outputList组成最全扩展集合
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> pipeList = map1.get("pipe");
                if (pipeList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < pipeList.size(); i++) {
                        Map<String, String> map3 = pipeList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();

                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        outputList.add(map2);
                    }
                }
            }
            List<Map<String, String>> list = nurseFileMapper.queryOtherPipe();
            if (list != null && list.size() >= 0) {
                if (isAll == 0) {
                    for (Map<String, String> filterPipeMap : outputList) {
                        Integer count = list.size(); // 每次循环更新list长度
                        for (int i = 0; i < count; i++) {
                            Map<String, String> srcPipeMap = list.get(i);
                            if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {

                                list.remove(srcPipeMap);
                                break;
                            }
                        }
                    }
                }

                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他类型导管");
            }
        } else if (type.equals(RemarkTypeEnum.ASSESS_PROJECTS.getEnumValue())) {

            // 获取评估名称基础数据元selections
            List<Map<String, String>> outputList = nurseFileMapper.queryEstimateElementSelections();
            // 获取当前患者自定义导管扩展，填入outputList组成最全扩展集合
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> assessList = map1.get("assess");
                if (assessList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < assessList.size(); i++) {
                        Map<String, String> map3 = assessList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();

                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        outputList.add(map2);
                    }
                }
            }


            List<Map<String, String>> list = nurseFileMapper.queryOtherAssess();
            if (list != null && list.size() >= 0) {
                for (Map<String, String> filterPipeMap : outputList) {
                    Integer count = list.size(); // 每次循环更新list长度
                    for (int i = 0; i < count; i++) {
                        Map<String, String> srcPipeMap = list.get(i);
                        if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {

                            list.remove(srcPipeMap);
                            break;
                        }
                    }
                }

                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他评估类型");
            }

        } else if (type.equals(RemarkTypeEnum.CONSCIOUS.getEnumValue())) {
            // 获取意识基础数据元selections
            List<Map<String, String>> consciousList = nurseFileMapper.queryConsciousElementSelections();
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> assessList = map1.get("realize");
                if (assessList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < assessList.size(); i++) {
                        Map<String, String> map3 = assessList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();
                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        consciousList.add(map2);
                    }
                }
            }
            List<Map<String, String>> list = nurseFileMapper.queryOtherRealize();
            if (list != null && list.size() >= 0) {
                for (Map<String, String> filterPipeMap : consciousList) {
                    Integer count = list.size(); // 每次循环更新list长度
                    for (int i = 0; i < count; i++) {
                        Map<String, String> srcPipeMap = list.get(i);
                        if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {
                            list.remove(srcPipeMap);
                            break;
                        }
                    }
                }
                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他评估类型");
            }


        } else if (type.equals(RemarkTypeEnum.MIND.getEnumValue())) {
            // 获取意识基础数据元selections
            List<Map<String, String>> mindList = nurseFileMapper.queryCommonDictionryValues("ck_jljszd");
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> expandMindsList = map1.get("mind");
                if (expandMindsList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < expandMindsList.size(); i++) {
                        Map<String, String> map3 = expandMindsList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();
                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        mindList.add(map2);
                    }
                }
            }
            List<Map<String, String>> list = nurseFileMapper.queryCommonDictionryValues("ck_jlqtjszd");
            if (list != null && list.size() >= 0) {
                for (Map<String, String> filterPipeMap : mindList) {
                    Integer count = list.size(); // 每次循环更新list长度
                    for (int i = 0; i < count; i++) {
                        Map<String, String> srcPipeMap = list.get(i);
                        if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {
                            list.remove(srcPipeMap);
                            break;
                        }
                    }
                }
                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他精神状态");
            }


        } else if (type.equals(RemarkTypeEnum.OXYGEN_WAY.getEnumValue())) {
            // 获取意识基础数据元selections
            List<Map<String, String>> oxygenList = nurseFileMapper.queryCommonDictionryValues("ck_jlxyfszd");
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> expandOxygenList = map1.get("oxygen");
                if (expandOxygenList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < expandOxygenList.size(); i++) {
                        Map<String, String> map3 = expandOxygenList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();
                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        oxygenList.add(map2);
                    }
                }
            }
            List<Map<String, String>> list = nurseFileMapper.queryCommonDictionryValues("ck_jlqtxyfszd");
            if (list != null && list.size() >= 0) {
                for (Map<String, String> filterPipeMap : oxygenList) {
                    Integer count = list.size(); // 每次循环更新list长度
                    for (int i = 0; i < count; i++) {
                        Map<String, String> srcPipeMap = list.get(i);
                        if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {
                            list.remove(srcPipeMap);
                            break;
                        }
                    }
                }
                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他吸氧方式");
            }


        } else if (type.equals(RemarkTypeEnum.NEW_BABY_PIPES.getEnumValue())) {
            // 获取意识基础数据元selections
            List<Map<String, String>> newbodyList = nurseFileMapper.queryCommonDictionryValues("ck_jlxsedgzd");
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> expandNewbodyList = map1.get("newpipe");
                if (expandNewbodyList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < expandNewbodyList.size(); i++) {
                        Map<String, String> map3 = expandNewbodyList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();
                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        newbodyList.add(map2);
                    }
                }
            }
            List<Map<String, String>> list = nurseFileMapper.queryOtherPipe();

            if (list != null && list.size() >= 0) {
                if (isAll == 0) {
                    for (Map<String, String> filterPipeMap : newbodyList) {
                        Integer count = list.size(); // 每次循环更新list长度
                        for (int i = 0; i < count; i++) {
                            Map<String, String> srcPipeMap = list.get(i);
                            if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {
                                list.remove(srcPipeMap);
                                break;
                            }
                        }
                    }
                }
                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他导管");
            }


        } else if (type.equals(RemarkTypeEnum.NEW_BABY_ASSESS_PROJECTS.getEnumValue())) {
            // 获取意识基础数据元selections
            List<Map<String, String>> newbodyAssessList = nurseFileMapper.queryCommonDictionryValues("ck_jlxsepgxmzd");
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> expandNewbodyAssessList = map1.get("newassess");
                if (expandNewbodyAssessList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < expandNewbodyAssessList.size(); i++) {
                        Map<String, String> map3 = expandNewbodyAssessList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();
                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        newbodyAssessList.add(map2);
                    }
                }
            }
            List<Map<String, String>> list = nurseFileMapper.queryOtherAssess();
            if (list != null && list.size() >= 0) {
                for (Map<String, String> filterPipeMap : newbodyAssessList) {
                    Integer count = list.size(); // 每次循环更新list长度
                    for (int i = 0; i < count; i++) {
                        Map<String, String> srcPipeMap = list.get(i);
                        if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {
                            list.remove(srcPipeMap);
                            break;
                        }
                    }
                }
                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他导管");
            }


        } else if (type.equals(RemarkTypeEnum.CHILD_ASSESS_PROJECTS.getEnumValue())) {
            // 获取意识基础数据元selections
            List<Map<String, String>> childAssessList = nurseFileMapper.queryCommonDictionryValues("ck_jlekpgmczd");
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> expandChildAssessList = map1.get("childassess");
                if (expandChildAssessList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < expandChildAssessList.size(); i++) {
                        Map<String, String> map3 = expandChildAssessList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();
                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        childAssessList.add(map2);
                    }
                }
            }
            List<Map<String, String>> list = nurseFileMapper.queryOtherAssess();
            if (list != null && list.size() >= 0) {
                for (Map<String, String> filterPipeMap : childAssessList) {
                    Integer count = list.size(); // 每次循环更新list长度
                    for (int i = 0; i < count; i++) {
                        Map<String, String> srcPipeMap = list.get(i);
                        if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {
                            list.remove(srcPipeMap);
                            break;
                        }
                    }
                }
                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他项目名称");
            }

        } else {
            return ResultGenerator.genFailedResult("未定义当前类型");
        }

    }

    @Override
    public Result getOtherPipes(String type, String fileIndexId) {
        Map<String, Object> data = new HashMap<>();
        if (type.equals(RemarkTypeEnum.IN_OUT_PIPES.getEnumValue())) { // type=1 导管，type=2 评估项目

            // 获取出量名称基础数据元selections
            List<Map<String, String>> outputList = nurseFileMapper.queryOutputElementSelections();
            // 获取当前患者自定义导管扩展，填入outputList组成最全扩展集合
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> pipeList = map1.get("pipe");
                if (pipeList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < pipeList.size(); i++) {
                        Map<String, String> map3 = pipeList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();

                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        outputList.add(map2);
                    }
                }
            }
            List<Map<String, String>> list = nurseFileMapper.queryOtherPipe();
            if (list != null && list.size() >= 0) {

                for (Map<String, String> filterPipeMap : outputList) {
                    Integer count = list.size(); // 每次循环更新list长度
                    for (int i = 0; i < count; i++) {
                        Map<String, String> srcPipeMap = list.get(i);
                        if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {

                            list.remove(srcPipeMap);
                            break;
                        }
                    }
                }

                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他类型导管");
            }
        } else if (type.equals(RemarkTypeEnum.ASSESS_PROJECTS.getEnumValue())) {

            // 获取评估名称基础数据元selections
            List<Map<String, String>> outputList = nurseFileMapper.queryEstimateElementSelections();
            // 获取当前患者自定义导管扩展，填入outputList组成最全扩展集合
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> assessList = map1.get("assess");
                if (assessList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < assessList.size(); i++) {
                        Map<String, String> map3 = assessList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();

                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        outputList.add(map2);
                    }
                }
            }


            List<Map<String, String>> list = nurseFileMapper.queryOtherAssess();
            if (list != null && list.size() >= 0) {
                for (Map<String, String> filterPipeMap : outputList) {
                    Integer count = list.size(); // 每次循环更新list长度
                    for (int i = 0; i < count; i++) {
                        Map<String, String> srcPipeMap = list.get(i);
                        if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {

                            list.remove(srcPipeMap);
                            break;
                        }
                    }
                }

                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他评估类型");
            }

        } else if (type.equals(RemarkTypeEnum.CONSCIOUS.getEnumValue())) {
            // 获取意识基础数据元selections
            List<Map<String, String>> consciousList = nurseFileMapper.queryConsciousElementSelections();
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> assessList = map1.get("realize");
                if (assessList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < assessList.size(); i++) {
                        Map<String, String> map3 = assessList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();
                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        consciousList.add(map2);
                    }
                }
            }
            List<Map<String, String>> list = nurseFileMapper.queryOtherRealize();
            if (list != null && list.size() >= 0) {
                for (Map<String, String> filterPipeMap : consciousList) {
                    Integer count = list.size(); // 每次循环更新list长度
                    for (int i = 0; i < count; i++) {
                        Map<String, String> srcPipeMap = list.get(i);
                        if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {
                            list.remove(srcPipeMap);
                            break;
                        }
                    }
                }
                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他评估类型");
            }


        } else if (type.equals(RemarkTypeEnum.MIND.getEnumValue())) {
            // 获取意识基础数据元selections
            List<Map<String, String>> mindList = nurseFileMapper.queryCommonDictionryValues("ck_jljszd");
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> expandMindsList = map1.get("mind");
                if (expandMindsList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < expandMindsList.size(); i++) {
                        Map<String, String> map3 = expandMindsList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();
                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        mindList.add(map2);
                    }
                }
            }
            List<Map<String, String>> list = nurseFileMapper.queryCommonDictionryValues("ck_jlqtjszd");
            if (list != null && list.size() >= 0) {
                for (Map<String, String> filterPipeMap : mindList) {
                    Integer count = list.size(); // 每次循环更新list长度
                    for (int i = 0; i < count; i++) {
                        Map<String, String> srcPipeMap = list.get(i);
                        if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {
                            list.remove(srcPipeMap);
                            break;
                        }
                    }
                }
                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他精神状态");
            }


        } else if (type.equals(RemarkTypeEnum.OXYGEN_WAY.getEnumValue())) {
            // 获取意识基础数据元selections
            List<Map<String, String>> oxygenList = nurseFileMapper.queryCommonDictionryValues("ck_jlxyfszd");
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> expandOxygenList = map1.get("oxygen");
                if (expandOxygenList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < expandOxygenList.size(); i++) {
                        Map<String, String> map3 = expandOxygenList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();
                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        oxygenList.add(map2);
                    }
                }
            }
            List<Map<String, String>> list = nurseFileMapper.queryCommonDictionryValues("ck_jlqtxyfszd");
            if (list != null && list.size() >= 0) {
                for (Map<String, String> filterPipeMap : oxygenList) {
                    Integer count = list.size(); // 每次循环更新list长度
                    for (int i = 0; i < count; i++) {
                        Map<String, String> srcPipeMap = list.get(i);
                        if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {
                            list.remove(srcPipeMap);
                            break;
                        }
                    }
                }
                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他吸氧方式");
            }


        } else if (type.equals(RemarkTypeEnum.NEW_BABY_PIPES.getEnumValue())) {
            // 获取意识基础数据元selections
            List<Map<String, String>> newbodyList = nurseFileMapper.queryCommonDictionryValues("ck_jlxsedgzd");
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> expandNewbodyList = map1.get("newpipe");
                if (expandNewbodyList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < expandNewbodyList.size(); i++) {
                        Map<String, String> map3 = expandNewbodyList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();
                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        newbodyList.add(map2);
                    }
                }
            }
            List<Map<String, String>> list = nurseFileMapper.queryOtherPipe();

            if (list != null && list.size() >= 0) {
                for (Map<String, String> filterPipeMap : newbodyList) {
                    Integer count = list.size(); // 每次循环更新list长度
                    for (int i = 0; i < count; i++) {
                        Map<String, String> srcPipeMap = list.get(i);
                        if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {
                            list.remove(srcPipeMap);
                            break;
                        }
                    }
                }
                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他导管");
            }


        } else if (type.equals(RemarkTypeEnum.NEW_BABY_ASSESS_PROJECTS.getEnumValue())) {
            // 获取意识基础数据元selections
            List<Map<String, String>> newbodyAssessList = nurseFileMapper.queryCommonDictionryValues("ck_jlxsepgxmzd");
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> expandNewbodyAssessList = map1.get("newassess");
                if (expandNewbodyAssessList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < expandNewbodyAssessList.size(); i++) {
                        Map<String, String> map3 = expandNewbodyAssessList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();
                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        newbodyAssessList.add(map2);
                    }
                }
            }
            List<Map<String, String>> list = nurseFileMapper.queryOtherAssess();
            if (list != null && list.size() >= 0) {
                for (Map<String, String> filterPipeMap : newbodyAssessList) {
                    Integer count = list.size(); // 每次循环更新list长度
                    for (int i = 0; i < count; i++) {
                        Map<String, String> srcPipeMap = list.get(i);
                        if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {
                            list.remove(srcPipeMap);
                            break;
                        }
                    }
                }
                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他导管");
            }


        } else if (type.equals(RemarkTypeEnum.CHILD_ASSESS_PROJECTS.getEnumValue())) {
            // 获取意识基础数据元selections
            List<Map<String, String>> childAssessList = nurseFileMapper.queryCommonDictionryValues("ck_jlekpgmczd");
            String recordJson = nurseFileMapper.queryExtends(fileIndexId);
            if (recordJson != null) {
                Map<String, List<Map<String, String>>> map1 = JSON.parseObject(recordJson, Map.class);

                // 出量管道
                List<Map<String, String>> expandChildAssessList = map1.get("childassess");
                if (expandChildAssessList != null) {
                    // 依次取出插入的名称拼接返回
                    for (int i = 0; i < expandChildAssessList.size(); i++) {
                        Map<String, String> map3 = expandChildAssessList.get(i);
                        String currName = map3.get("name");
                        Map<String, String> map2 = new HashMap<>();
                        map2.put("dataText", currName);
                        map2.put("id", map3.get("del"));
                        map2.put("dataValue", "");
                        childAssessList.add(map2);
                    }
                }
            }
            List<Map<String, String>> list = nurseFileMapper.queryOtherAssess();
            if (list != null && list.size() >= 0) {
                for (Map<String, String> filterPipeMap : childAssessList) {
                    Integer count = list.size(); // 每次循环更新list长度
                    for (int i = 0; i < count; i++) {
                        Map<String, String> srcPipeMap = list.get(i);
                        if (filterPipeMap.get("dataText").substring(1).equals(srcPipeMap.get("dataText")) || filterPipeMap.get("dataText").equals(srcPipeMap.get("dataText"))) {
                            list.remove(srcPipeMap);
                            break;
                        }
                    }
                }
                return ResultGenerator.genOkResult(list);
            } else {
                return ResultGenerator.genFailedResult("未取得其他项目名称");
            }

        } else {
            return ResultGenerator.genFailedResult("未定义当前类型");
        }

    }


    @Override
    @SuppressWarnings("unchecked")
    public Result saveRemark(String type, String fileIndexId, String name) {
        if (StringUtils.isBlank(name)) {
            return ResultGenerator.genOkResult("名称不能为空");
        }
        Result pipResult = getOtherPipes3(type, fileIndexId, 1);
        List<Map<String, String>> list = (List<Map<String, String>>) pipResult.getData();

        // 1获取EMR_FILE_INDEX中记录的NURSE_CUSTOMIZE_EXPAND获取出量名称和项目名称的扩展记录
        String recordJson = nurseFileMapper.queryExtends(fileIndexId);
        RemarkTypeEnum remarkTypeEnum = null;
        for (RemarkTypeEnum enumTemp : RemarkTypeEnum.values()) {
            if (type.equals(enumTemp.getEnumValue())) {
                remarkTypeEnum = enumTemp;
                break;
            }
        }
        if (remarkTypeEnum == null) {
            return ResultGenerator.genOkResult("当前类型暂未支持");
        }
        List<Map<String, String>> options = nurseFileMapper.queryCommonDictionryValues(remarkTypeEnum.getVarCode());

        Map<String, List<Map<String, String>>> nurseCustomizeExpand;
        if (StringUtils.isBlank(recordJson)) {
            Map<String, Object> data = this.getCustomizeMap(options, remarkTypeEnum.getTypeValue(), name);
            //只包含本次新增内容
            nurseCustomizeExpand = (Map<String, List<Map<String, String>>>) data.get("nurseCustomizeExpand");
            options = (List<Map<String, String>>) data.get("options");
        } else {
            nurseCustomizeExpand = JSON.parseObject(recordJson, Map.class);
            Map<String, Object> data = this.getCustomizeMap2(nurseCustomizeExpand, options, remarkTypeEnum.getTypeValue(), name);
            //nurseCustomizeExpand 包含历史新增的 以及本次新增的内容
            options = (List<Map<String, String>>) data.get("options");
        }

        for (Map<String, String> allItem : list) {
            for (Map<String, String> item : options) {
                String itemStr = item.get("dataText").substring(1, item.get("dataText").length());
                if (allItem.get("dataText").equals(itemStr)) {
                    item.put("dataValue", allItem.get("dataValue"));
                    item.put("dataId", allItem.get("id"));
                }
            }
        }
        // 转为json串更新到EMR.EMR_FILE_INDEX中
        String jsonString = JSON.toJSONString(nurseCustomizeExpand, SerializerFeature.WriteNullStringAsEmpty);
        nurseFileMapper.updateCustomizeExpand(jsonString, fileIndexId);
        return ResultGenerator.genOkResult(options);
    }


    private Map<String, Object> getCustomizeMap(List<Map<String, String>> options, String typeValue, String name) {
        Map<String, Object> data = new HashMap<>();
        Map<String, List<Map<String, String>>> nurseCustomizeExpand = new HashMap<>();
        for (Map<String, String> option : options) {
            String optionName = option.get("dataText");
            if (optionName.equals(name) || optionName.substring(1).equals(name)) {
                throw new ServiceException("已存在同名内容");
            }
        }
        String numStr = longNumStr.substring(options.size(), options.size() + 1);
        String fullName = numStr + name;
        //需要返回前台的内容
        Map<String, String> map1 = new HashMap<>();
        map1.put("dataText", fullName);
        map1.put("id", "0");
        map1.put("dataValue", "");
        options.add(map1);
        //存入数据库的内容
        List<Map<String, String>> tempList = new ArrayList<>();
        Map<String, String> map2 = new HashMap<>();
        map2.put("name", name);
        map2.put("del", "0");
        tempList.add(map2);
        nurseCustomizeExpand.put(typeValue, tempList);
        data.put("nurseCustomizeExpand", nurseCustomizeExpand);
        data.put("options", options);
        return data;
    }

    private Map<String, Object> getCustomizeMap2(Map<String, List<Map<String, String>>> map, List<Map<String, String>> options, String typeValue, String name) {
        Map<String, Object> data = new HashMap<>();
        // 如果是管道类型，需要先判断是否在默认管道中包含，因为现在默认导管前带有圆圈数字符号（后续可能去除）,需要对options里元素做两次比较
        for (Map<String, String> option : options) {
            String optionName = option.get("dataText");
            if (optionName.equals(name) || optionName.substring(1).equals(name)) {
                throw new ServiceException("已存在同名内容");
            }
        }
        List<Map<String, String>> tempList = map.get(typeValue);
        if (tempList != null) {
            for (Map map1 : tempList) {
                if (map1.get("name").equals(name)) {
                    throw new ServiceException("已存在同名内容");
                }
            }
            Map<String, String> map2 = new HashMap<>();
            map2.put("name", name);
            map2.put("del", "0");
            //map.get(typeValue)即tempList 改变tempList值会改变整个map的值
            tempList.add(map2);
        } else {
            tempList = new ArrayList<>();
            Map<String, String> map2 = new HashMap<>();
            map2.put("name", name);
            map2.put("del", "0");
            tempList.add(map2);
            map.put(typeValue, tempList);
        }
        // 根据varCode获取出量名称数据元并获取数据元的selections,将新增名称拼接返回
        Integer optionsSrcCount = options.size();
        // 依次取出插入的名称拼接返回
        for (int i = 0; i < tempList.size(); i++) {
            Map<String, String> map2 = tempList.get(i);
            String currName = map2.get("name");
            String numStr = longNumStr.substring(optionsSrcCount + i, optionsSrcCount + i + 1);
            String fullName = numStr + currName;
            Map<String, String> map1 = new HashMap<>();
            map1.put("dataText", fullName);
            map1.put("id", map2.get("del"));
            map1.put("dataValue", "");
            options.add(map1);
        }
        data.put("options", options);
        return data;
    }

    @Override
    public Result deleteRemark(String fileIndexId, String type, String name) {
        // 获取患者住院号
        String inpatNum = nurseFileIndexMapper.queryInpatNumByFileIndexId(fileIndexId);
        List<Map<String, String>> qouteList = nurseFileDataDetailMapper.queryRemarkQouteList(inpatNum, name);
        if (ArrayUtils.isNotEmpty(qouteList.toArray())) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("qouteList", qouteList);
            return ResultGenerator.genOkResult(resultMap);
        }
        RemarkTypeEnum remarkTypeEnum = null;
        for (RemarkTypeEnum enumTemp : RemarkTypeEnum.values()) {
            if (type.equals(enumTemp.getEnumValue())) {
                remarkTypeEnum = enumTemp;
                break;
            }
        }
        if (remarkTypeEnum == null) {
            return ResultGenerator.genOkResult("当前类型暂未支持");
        }
        // 1获取EMR_FILE_INDEX中记录的NURSE_CUSTOMIZE_EXPAND获取出量名称和项目名称的扩展记录
        String recordJson = nurseFileMapper.queryExtends(fileIndexId);
        List<Map<String, String>> options = nurseFileMapper.queryCommonDictionryValues(remarkTypeEnum.getVarCode());
        if (StringUtils.isNotBlank(recordJson)) {
            String tempName = name.substring(1);
            Map<String, List<Map<String, String>>> map = JSON.parseObject(recordJson, Map.class);
            List<Map<String, String>> options2 = this.getDelTempList(map, options, remarkTypeEnum.getTypeValue(), tempName, inpatNum, fileIndexId);
            return ResultGenerator.genOkResult(options2);
        }
        return ResultGenerator.genOkResult(options);
    }

    private List<Map<String, String>> getDelTempList(Map<String, List<Map<String, String>>> map, List<Map<String, String>> options, String typeValue, String tempName, String inpatNum, String fileIndexId) {

        List<Map<String, String>> pipeList = map.get(typeValue);
        if (pipeList != null) {
            Integer count = pipeList.size();
            for (int i = 0; i < count; i++) {
                Map map1 = pipeList.get(i);
                if (map1.get("name").equals(tempName) && map1.get("del").equals("0")) {
                    pipeList.remove(map1);
                    map.put(typeValue, pipeList);
                    // 转为json串更新到EMR.EMR_FILE_INDEX中
                    String jsonString = JSON.toJSONString(map, SerializerFeature.WriteNullStringAsEmpty);
                    nurseFileMapper.updateCustomizeExpand(jsonString, fileIndexId);
                    // 数组长度长于当前删除的备注
                    if (count - 1 > i) {
                        Integer optionsSrcCount = options.size();
                        for (int j = i; j < count - 1; j++) {
                            Map map2 = pipeList.get(j);
                            String beforeNumStr = longNumStr.substring(optionsSrcCount + 1 + j, optionsSrcCount + 1 + j + 1);
                            String afterNumStr = longNumStr.substring(optionsSrcCount + j, optionsSrcCount + j + 1);
                            String beforeName = beforeNumStr + map2.get("name");
                            String afterName = afterNumStr + map2.get("name");
                            nurseFileDataDetailMapper.updateRemarkDataValue(inpatNum, null, beforeName, afterName);
                        }
                    }
                    break;
                }
            }
        }
        if (CollectionUtils.isNotEmpty(pipeList)) {
            Integer optionsSrcCount = options.size();
            // 依次取出插入的名称拼接返回
            for (int i = 0; i < pipeList.size(); i++) {
                Map<String, String> map3 = pipeList.get(i);
                String currName = map3.get("name");
                String numStr = longNumStr.substring(optionsSrcCount + i, optionsSrcCount + i + 1);
                String fullName = numStr + currName;
                Map<String, String> map2 = new HashMap<>();
                map2.put("dataText", fullName);
                map2.put("id", map3.get("del"));
                map2.put("dataValue", "");
                options.add(map2);
            }
        }
        return options;
    }

    /**
     * 获取数据元下拉
     *
     * @param elementId    数据元ID
     * @param word         查询字符
     * @param dataCode     值域主键
     * @param page         页号
     * @param pageSize
     * @param parentSerial 父值域主键
     * @param varCode      系统参数
     * @return
     */
    public List<Map<String, String>> querySelections(String elementId, String word, String dataCode, int page, int pageSize, String parentSerial, String varCode, String wardId, String isWeight) {
        if ("hlxz".equals(varCode)) {
            if (1 == page) {
                return nurseFileMapper.queryDataSetElementValueByName("性状（护理）", word, dataCode);
            } else {
                return Collections.EMPTY_LIST;
            }
        }
        String pinyin;
        if (StringUtils.isBlank(elementId)) {
            elementId = nurseFileMapper.queryVarValueByVarCode(varCode);
        }

        if (StringUtils.isBlank(elementId)) {
            logger.error("数据元获取下拉项时，数据元id为空！");
            return new ArrayList<>();
        }

        try {
            pinyin = ChineseCharactersCode.getPinyinCode(word);
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            logger.error("转拼音出错，字符异常。");
            return new ArrayList<>();
        }
        boolean isPinyin = false;
        if (word.equals(pinyin)) {
            isPinyin = true;
        }

        // 转义特殊字符 后续like查询以 / 作为转义字符
        String likeTerm = word.replaceAll("/", "//").replaceAll("%", "/%").replaceAll("_", "/_");

        // 查询医疗术语
        if (COMPOSE_DICT.equals(varCode)) {
            return emrFileMapper.queryComposeSelections(elementId, likeTerm, word, isPinyin, dataCode, page, pageSize);
        }

        List<Map<String, String>> querSelectionsList = null;
        if (StringUtils.isBlank(word)) {
            PageHelper.startPage(page, pageSize);
            querSelectionsList = nurseElementMapper.queryNoSearchSelections(elementId, dataCode, parentSerial, wardId, isWeight);
        } else {
            querSelectionsList = nurseElementMapper.querySelections(elementId, pinyin.toUpperCase(), word, isPinyin, dataCode, page, pageSize, parentSerial, wardId, isWeight);
        }
        return querSelectionsList;
    }

    public Map<String, String> getInHospitalLocationInfo(String recordTime, String inpatNum, String bedNo) {
        Map<String, String> infoMap = new HashMap<>();
        infoMap.put("wardId", "");
        infoMap.put("deptId", "");
        infoMap.put("bedNo", "");
        // 转科记录
        Map<String, String> transMap = nursePatientMapper.queryTransRecord(DateUtil.stringToDate(recordTime), inpatNum);
        if (transMap != null) {
            infoMap.put("wardId", transMap.get("wardId") == null ? "" : transMap.get("wardId"));
            infoMap.put("deptId", transMap.get("deptId") == null ? "" : transMap.get("deptId"));
            infoMap.put("bedNo", transMap.get("bedNo") == null ? "" : transMap.get("bedNo"));
        } else {
            // 查询个人病区科室及床号信息
            Map<String, String> map = nursePatientMapper.queryDeptInfo(inpatNum);
            if (map != null) {
                infoMap.put("wardId", map.get("wardId") == null ? "" : map.get("wardId"));
                infoMap.put("deptId", map.get("deptId") == null ? "" : map.get("deptId"));
                infoMap.put("bedNo", map.get("bedNo") == null ? "" : map.get("bedNo"));
            }

        }

        if (StringUtils.isNotBlank(bedNo) && !bedNo.equals("0")) {
            // 床号有效
            infoMap.put("bedNo", bedNo);
        }

        return infoMap;
    }

    @Override
    public List<Assembly> associateByWords(String word, String varCode) {
        if (word.isEmpty()) {
            return Collections.EMPTY_LIST;
        }
        boolean isNumeric = Pattern.matches("^-{0,1}\\+{0,1}\\d+\\.{0,1}\\d*$", word);
        if (isNumeric) { // 参数是数字 且不在诊断节点下
            List<Element> elements = nurseElementMapper.getNumberElements(word);
            return elements.stream().map(element -> {
                Assembly assembly = new Assembly();
                assembly.setSort(3);
                assembly.setName(element.getValue() + (element.getUnit() == null ? "" : element.getUnit()));
                element.setDataValue(element.getValue());
                assembly.setType("elementDataValue");
                assembly.setElement(element);
                return assembly;
            }).collect(Collectors.toList());
        }
        String pinyin;
        try {
            pinyin = ChineseCharactersCode.getPinyinCode(word);
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            logger.error("转拼音出错，字符异常。");
            return new ArrayList<>();
        }
        boolean isPinyin = false;
        if (word.equals(pinyin)) {
            isPinyin = true;
        }
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        List<Assembly> assemblyList = nurseElementMapper.queryAssemblyFromMedical(isPinyin, pinyin.toUpperCase(), word, userId);
        if (!assemblyList.isEmpty()) {
            assemblyList.parallelStream().forEach(assembly -> {
                Element element = new Element();
                assembly.setSort(1);
                element.setType(assembly.getType());
                if ("1".equals(assembly.getRoleType())) {
                    element.setName("医疗术语");
                } else {
                    element.setName("医疗术语(科室)");
                }
                assembly.setElement(element);
                assembly.setType("medical");
            });
        }
        List<Map<String, String>> basicDataList = nurseElementMapper.queryBasicData(word.toUpperCase());

        basicDataList.stream().forEach(basicData -> {
            List<Element> elements = nurseElementMapper.queryElementByBasicData(basicData.get("dataId"), "");
            for (Element element : elements) {
                if (element == null) {
                    logger.error("无 {}", basicData);
                    continue;
                }
                Assembly assembly = new Assembly();
                assembly.setSort(2);
                assembly.setId(basicData.get("id"));
                assembly.setName(basicData.get("name"));
                element.setDataValue(basicData.get("dataText"));
                element.setDataCode(basicData.get("id"));
                element.setShowText(basicData.get("showText"));
                assembly.setElement(element);
                assembly.setType("elementValue");
//                if (basicData.get("name").equalsIgnoreCase(word)) {
//                    assembly.setSort(0);
//                }
                assemblyList.add(assembly);

            }
        });

        //数据元->
        List<Element> elements = nurseElementMapper.queryElement(isPinyin, pinyin.toUpperCase(), word);
        elements.forEach(element -> {
            Assembly assembly = new Assembly();
            assembly.setSort(3);
            assembly.setId(element.getId());
            assembly.setName(element.getName());
            assembly.setType("element");
            Element temp = new Element();
            temp.setName("数据元");
            temp.setType(element.getType());
            temp.setId(element.getId());
            temp.setMin(element.getMin());
            temp.setMax(element.getMax());
            temp.setUnit(element.getUnit());
            temp.setVarCode(element.getVarCode());
            temp.setElementPropertyFormat(element.getElementPropertyFormat());
            assembly.setElement(temp);
//            if (element.getName().equalsIgnoreCase(word)) {
//                assembly.setSort(0);
//            }
            assemblyList.add(assembly);

        });
        assemblyList.sort(Comparator.comparingInt(Assembly::getSort));
        return assemblyList;
    }

    @Override
    public List<String> getUnits(String elementId) {
        if (org.springframework.util.StringUtils.isEmpty(elementId)) {
            logger.error("数字型数据元获取单位下拉项时，数据元id为空！");
            return new ArrayList<>();
        }
        List<String> options = nurseFileIndexMapper.getUnits(elementId);
        return options;
    }


    @Override
    @Transactional
    public Result transData(String inpatNum) {
        // 获取文书
//        EmrFileIndexEntity emrFileIndexEntity = nurseTransMapper.queryEmrFileIndex(inpatNum);

        nurseTransMapper.transFileIndexData(inpatNum);

        NurseFileIndexEntity nurseFileIndexEntity = nurseFileIndexMapper.queryIndexByRecordType("0", inpatNum);
        if (nurseFileIndexEntity != null) {
            List<EmrNursingcareRelationEntity> list = nurseTransMapper.queryEmrNursingcarRelations(nurseFileIndexEntity.getFileIndexId());
            if (ArrayUtils.isEmpty(list.toArray())) {
                throw new ServiceException("无文书详细记录");
            }
            list.parallelStream().forEach(nursingcareRelationEntity -> {
                logger.info("当前记录的时间：{}", nursingcareRelationEntity.getGmtCreate());
                if ("1".equals(nursingcareRelationEntity.getNursingcareType())) {
                    // 一般类型
//                    nurseTransMapper.transFileDataData(nursingcareRelationEntity.getEmrFileId(), String.valueOf(nursingcareRelationEntity.getGroupNo()));

                } else {
                    // 总结类型
                }
                // 转移记录
//                nurseTransMapper.transFileDataData(nursingcareRelationEntity.getEmrFileId(), nursingcareRelationEntity.getGroupNo());


            });
        }


        return null;
    }

    @Override
    public List<Map<String, String>> searchBlood(String searchName) {
        return nurseFileMapper.queryBloodsByElementName(searchName);
    }

    @Override
    public Result getApgarRecord(String inpatNum) {
        List<MedicalDTO> result = new ArrayList<>();
        if (inpatNum.contains("B")) {
            //母婴同室新生儿护理记录
            NursePatientMsgDTO dto = nursePatientMapper.getPatientInfo(inpatNum);
            result = this.getMedicalDtoByInpatNum(inpatNum, result, dto.getPatName());
            return ResultGenerator.genOkResult(result);
        } else {
            //获取病人产时2记录id inpatNum为大人的inpatNum
            NurseFileDataEntity fileDataEntity = nurseFileDataMapper.queryOnlyRecord(NurseFileTypeEnum.LabourB.getEnumValue(), inpatNum);
            if (fileDataEntity != null) {
                String fileDataId = fileDataEntity.getFileDataId();
                List<String> neonatusGender = nurseFileDataDetailMapper.getNeonatusGender(fileDataId);//获取新生儿性别 判断有几个新生儿
                if (!CollectionUtils.isEmpty(neonatusGender)) {
                    NursePatientMsgDTO dto = nursePatientMapper.getPatientInfo(inpatNum);
                    String patName = dto.getPatName();
                    Integer male = 2, female = 2, unknown = 2, undefind = 2;
                    for (int i = 0; i < neonatusGender.size(); i++) {
                        String babyName = "";
                        String[] inpatInfo = inpatNum.split("-");
                        String inpatNumB = inpatInfo[0] + "B" + (i + 1) + "-" + inpatInfo[1]; //新生儿床号
                        if ("男性".equals(neonatusGender.get(i))) {
                            if (male > 2) {
                                babyName = patName + "之子" + (male - 1);
                            } else {
                                babyName = patName + "之子";
                            }
                            male += 1;
                        } else if ("女性".equals(neonatusGender.get(i))) {
                            if (female > 2) {
                                babyName = patName + "之女" + (female - 1);
                            } else {
                                babyName = patName + "之女";
                            }
                            female += 1;
                        } else if ("未知的性别".equals(neonatusGender.get(i))) {
                            if (unknown > 2) {
                                babyName = patName + "未知" + (unknown - 1);
                            } else {
                                babyName = patName + "未知";
                            }
                            unknown += 1;
                        } else if ("未说明的性别".equals(neonatusGender.get(i))) {
                            if (undefind > 2) {
                                babyName = patName + "未说明" + (undefind - 1);
                            } else {
                                babyName = patName + "未说明";
                            }
                            undefind += 1;
                        }
                        result = this.getMedicalDtoByInpatNum(inpatNumB, result, babyName);
                    }
                    return ResultGenerator.genOkResult(result);
                }
            }
            // 没有记录 返回空
            return ResultGenerator.genOkResult(result);
        }
    }


    private List<MedicalDTO> getMedicalDtoByInpatNum(String inpatNumB, List<MedicalDTO> result, String patName) {
        NurseFileDataEntity dataEntity = nurseFileDataMapper.queryOnlyRecord(NurseFileTypeEnum.ApgarScore.getEnumValue(), inpatNumB);
        if (dataEntity != null) {
            String fileDataId = dataEntity.getFileDataId();

            // 存在记录
            List<Map<String, String>> apgarDetail = nurseFileDataDetailMapper.queryApgarDetail(fileDataId);
            int apgarSize = apgarDetail.size();
            this.addMedicalDTO("文本数据元", patName, result);
            this.addMedicalDTO("标点符号", "，", result);
            if (apgarDetail.stream().anyMatch(map -> Integer.parseInt(map.get("DATA_VALUE")) < 8)) {//评分有小于8分的 显示详细
                for (int index = 0; index < apgarSize; index++) {
                    if (Integer.parseInt(apgarDetail.get(index).get("DATA_VALUE")) < 8) {
                        this.addOtherMedicalDTO(index, apgarDetail.get(index).get("DATA_VALUE") + "'", apgarDetail.get(index).get("PARENT_ID"), result, true, index + 1 == apgarSize);
                    } else {
                        this.addOtherMedicalDTO(index, apgarDetail.get(index).get("DATA_VALUE") + "'", apgarDetail.get(index).get("PARENT_ID"), result, false, index + 1 == apgarSize);
                    }
                }
            } else {
                this.addMedicalDTO("护理评估工具名称", "Apgar评分", result);
                this.addMedicalDTO("常用连接语", "为", result);
                for (int index = 0; index < apgarSize; index++) {
                    if (index == 0) {
                        this.addMedicalDTO("Apgar得分", apgarDetail.get(index).get("DATA_VALUE") + "'", result);
                    } else if (index == 1) {
                        this.addMedicalDTO("特殊字符", "-", result);
                        this.addMedicalDTO("Apgar得分", apgarDetail.get(index).get("DATA_VALUE") + "'", result);
                    } else {
                        this.addMedicalDTO("特殊字符", "-", result);
                        this.addMedicalDTO("Apgar得分", apgarDetail.get(index).get("DATA_VALUE") + "'", result);
                    }
                }
            }
        }
        return result;
    }

    private void addMedicalDTO(String elementName, String dataValue, List<MedicalDTO> result) {
        MedicalDTO medicalDTO = new MedicalDTO();
        Element element = nurseFileMapper.queryElementByName(elementName, dataValue);
        medicalDTO.setElement(element);
        SelvalueDTO selvalueDTO = new SelvalueDTO();
        selvalueDTO.setDataValue(dataValue);
        selvalueDTO.setDataCode(element.getDataCode());
        medicalDTO.setFileIndexDataEntity(selvalueDTO);
        result.add(medicalDTO);
    }

    private void addOtherMedicalDTO(int index, String dataValue, String parentId, List<MedicalDTO> result, boolean under8, boolean last) {
        this.addMedicalDTO("Apgar评分-下拉", (index == 0 ? 1 : index * 5) + "分钟评分", result);
        this.addMedicalDTO("常用连接语", "为", result);
        this.addMedicalDTO("Apgar得分", dataValue, result);
        this.addMedicalDTO("标点符号", "，", result);
        if (under8) {
            this.addMedicalDTO("护理总结用语", "其中", result);
            List<Map<String, String>> apgarScoreDetail = nurseFileDataDetailMapper.queryApgarScoreDetail(parentId);
            int size = apgarScoreDetail.size();
            for (int i = 0; i < size; i++) {
                Map<String, String> map = apgarScoreDetail.get(i);
                if ("ck_jlapgarxl".equals(map.get("VAR_CODE"))) {
                    this.addMedicalDTO("评估情况", "心率", result);
                    this.addMedicalDTO("Apgar心率-下拉", map.get("DATA_VALUE_REMARK"), result);
                    this.addMedicalDTO("Apgar扣分", "扣" + (2 - Integer.parseInt(map.get("DATA_VALUE"))) + "分", result);
                    if (i + 1 == size && last) {
                        this.addMedicalDTO("标点符号", "。", result);
                    } else {
                        this.addMedicalDTO("标点符号", "，", result);
                    }
                }
                if ("ck_jlapgarhx".equals(map.get("VAR_CODE"))) {
                    this.addMedicalDTO("评估情况", "呼吸", result);
                    this.addMedicalDTO("Apgar呼吸-下拉", map.get("DATA_VALUE_REMARK"), result);
                    this.addMedicalDTO("Apgar扣分", "扣" + (2 - Integer.parseInt(map.get("DATA_VALUE"))) + "分", result);
                    if (i + 1 == size && last) {
                        this.addMedicalDTO("标点符号", "。", result);
                    } else {
                        this.addMedicalDTO("标点符号", "，", result);
                    }
                }
                if ("ck_jlapgarjzl".equals(map.get("VAR_CODE"))) {
                    this.addMedicalDTO("评估情况", "呼吸", result);
                    this.addMedicalDTO("Apgar肌张力-下拉", map.get("DATA_VALUE_REMARK"), result);
                    this.addMedicalDTO("Apgar扣分", "扣" + (2 - Integer.parseInt(map.get("DATA_VALUE"))) + "分", result);
                    if (i + 1 == size && last) {
                        this.addMedicalDTO("标点符号", "。", result);
                    } else {
                        this.addMedicalDTO("标点符号", "，", result);
                    }
                }
                if ("ck_jlapgarfs".equals(map.get("VAR_CODE"))) {
                    this.addMedicalDTO("评估情况", "反射", result);
                    this.addMedicalDTO("Apgar反射-下拉", map.get("DATA_VALUE_REMARK"), result);
                    this.addMedicalDTO("Apgar扣分", "扣" + (2 - Integer.parseInt(map.get("DATA_VALUE"))) + "分", result);
                    if (i + 1 == size && last) {
                        this.addMedicalDTO("标点符号", "。", result);
                    } else {
                        this.addMedicalDTO("标点符号", "，", result);
                    }
                }
                if ("ck_jlapgarpfys".equals(map.get("VAR_CODE"))) {
                    this.addMedicalDTO("评估情况", "皮肤颜色", result);
                    this.addMedicalDTO("Apgar皮肤颜色-下拉", map.get("DATA_VALUE_REMARK"), result);
                    this.addMedicalDTO("Apgar扣分", "扣" + (2 - Integer.parseInt(map.get("DATA_VALUE"))) + "分", result);
                    if (i + 1 == size && last) {
                        this.addMedicalDTO("标点符号", "。", result);
                    } else {
                        this.addMedicalDTO("标点符号", "，", result);
                    }
                }
            }

        }
    }


    /**
     * 新生儿：年龄小于等于28天; --- 1
     * 患儿：年龄小于等于14岁大于28天; ---2
     * 患者：年龄大于14岁; --- 3
     */
    @Override
    public Result getCatalog(String deptId, String inpatNum) {
        //住院号为空时 不返回目录
        if (StringUtils.isBlank(inpatNum)) {
            return ResultGenerator.genOkResult();
        }
        Map<String, BigDecimal> patientAge = nursePatientMapper.getPatientAge(inpatNum);//获取病人年龄
        PatientInHospitalEntity patientInHospitalEntity = nursePatientMapper.selectPatientByInpatNum(inpatNum);
        int pAge = this.getPatientAge(patientInHospitalEntity);
        String applicableObjcet;
        if (patientAge.get("year").intValue() == 0 && patientAge.get("day").intValue() <= 28) {
            applicableObjcet = "1";
        } else if ((patientAge.get("year").intValue() == 0 && patientAge.get("day").intValue() > 28) || patientAge.get("year").intValue() <= 14) {
            applicableObjcet = "2";
        } else {
            applicableObjcet = "3";
        }
        List<NurseCatalogEntity> catalogEntities = nurseCatalogMapper.getFirstCatalog();
        List<NurseTree<NurseFormDTO>> trees = new ArrayList<>();
        List<String> ctlIds = new ArrayList<>();
        catalogEntities.stream().forEach(entity -> {
            if (entity.getApplicableObject().contains(applicableObjcet)) {
                if (NurseEnum.ROLE_TYPE_ONE.getIndex().equals(entity.getRoleType())) {
                    NurseTree<NurseFormDTO> tree = new NurseTree<>();
                    tree.setId(entity.getCtlId());
                    tree.setParentId(entity.getParentCtlId());
                    tree.setText(entity.getCtlName());
                    tree.setSortId(Integer.parseInt(entity.getSortId()));
                    ctlIds.add(entity.getCtlId());
                    trees.add(tree);
                } else {
                    if (entity.getDeptId().contains(deptId)) {
                        NurseTree<NurseFormDTO> tree = new NurseTree<>();
                        tree.setId(entity.getCtlId());
                        tree.setParentId(entity.getParentCtlId());
                        tree.setText(entity.getCtlName());
                        tree.setSortId(Integer.parseInt(entity.getSortId()));
                        trees.add(tree);
                        ctlIds.add(entity.getCtlId());
                    }
                }
            }
        });

        int finalPAge = pAge;
        ctlIds.stream().forEach(ctlId -> {
            List<NurseFormEntity> nurseForms = nurseCatalogMapper.getFromByCatalogId(ctlId);
            nurseForms.stream().forEach(form -> {
                if (form.getApplicableObject().contains(applicableObjcet)) {
                    if (NurseEnum.ROLE_TYPE_ONE.getIndex().equals(form.getRoleType())) {
                        NurseTree<NurseFormDTO> tree2 = new NurseTree<>();
                        tree2.setId(form.getFormId());
                        tree2.setParentId(form.getCtlId());
                        tree2.setText(form.getFormName());
                        tree2.setRecordType(form.getRecordType());
                        tree2.setSortId(Integer.parseInt(form.getSortId()));
                        tree2.setBasicdatavalueId(form.getBasicdatavalueId());
                        if(StringUtils.isBlank(form.getAgeFrom()) && StringUtils.isBlank(form.getAgeTo())){
                            trees.add(tree2);
                        }else if(StringUtils.isNotBlank(form.getAgeFrom()) && StringUtils.isNotBlank(form.getAgeTo())){
                            if(finalPAge >=Integer.parseInt(form.getAgeFrom()) && Integer.parseInt(form.getAgeTo())>= finalPAge){
                                trees.add(tree2);
                            }
                        }else if(StringUtils.isNotBlank(form.getAgeFrom())){
                            if(Integer.parseInt(form.getAgeFrom())>=finalPAge){
                                trees.add(tree2);
                            }
                        }else if(StringUtils.isNotBlank(form.getAgeTo())){
                            if(finalPAge>Integer.parseInt(form.getAgeTo())){
                                trees.add(tree2);
                            }
                        }

                    } else {
                        if (form.getDeptId().contains(deptId)) {
                            NurseTree<NurseFormDTO> tree2 = new NurseTree<>();
                            tree2.setId(form.getFormId());
                            tree2.setParentId(form.getCtlId());
                            tree2.setText(form.getFormName());
                            tree2.setRecordType(form.getRecordType());
                            tree2.setSortId(Integer.parseInt(form.getSortId()));
                            tree2.setBasicdatavalueId(form.getBasicdatavalueId());
                            if(StringUtils.isBlank(form.getAgeFrom()) && StringUtils.isBlank(form.getAgeTo())){
                                trees.add(tree2);
                            }else if(StringUtils.isNotBlank(form.getAgeFrom()) && StringUtils.isNotBlank(form.getAgeTo())){
                                if(finalPAge >=Integer.parseInt(form.getAgeFrom()) && Integer.parseInt(form.getAgeTo())>= finalPAge){
                                    trees.add(tree2);
                                }
                            }else if(StringUtils.isNotBlank(form.getAgeFrom())){
                                if(Integer.parseInt(form.getAgeFrom())>=finalPAge){
                                    trees.add(tree2);
                                }
                            }else if(StringUtils.isNotBlank(form.getAgeTo())){
                                if(finalPAge>Integer.parseInt(form.getAgeTo())){
                                    trees.add(tree2);
                                }
                            }

                        }
                    }
                }
            });
        });
        trees.sort(Comparator.comparingInt(NurseTree::getSortId));
        List<NurseTree<NurseFormDTO>> t = buildTree(trees, "9731069DB86B05FDE0537A5B14ACBCA9");
        return ResultGenerator.genOkResult(t.stream().filter(tree -> tree.getChildren().size() > 0));
    }

    /**
     * 获取年龄
     * @param patientInHospitalEntity
     * @return
     */
    public int getPatientAge(PatientInHospitalEntity patientInHospitalEntity){
        Integer ageYear = patientInHospitalEntity.getAgeYear();
        Integer ageMonth = patientInHospitalEntity.getAgeMonth();
        Integer ageDay = patientInHospitalEntity.getAgeDay();
        Integer ageHour = patientInHospitalEntity.getAgeHour();
        Integer ageMinute = patientInHospitalEntity.getAgeMinute();
        int age = 1;
        if(ageYear!=null){
            age=ageYear;
        }else if(ageMonth!=null){
        }else if(ageDay!=null){
        }else if(ageHour!=null){
        }else if(ageMinute!=null){
        }
        return age;
    }


    private <T> List<NurseTree<T>> buildTree(List<NurseTree<T>> nodes, String parentId) {
        if (nodes == null) {
            return null;
        }
        List<NurseTree<T>> topNodes = new ArrayList<>();
        for (NurseTree<T> children : nodes) {
            String pid = children.getParentId();
            if (pid == null || parentId.equals(pid)) {
                topNodes.add(children);
                continue;
            }
            for (NurseTree<T> parent : nodes) {
                String id = parent.getId();
                if (id != null && id.equals(pid)) {
                    parent.getChildren().add(children);
                    break;
                }
            }
        }
        return topNodes;
    }

    @Override
    public Result getCurrSystime() {
        return ResultGenerator.genOkResult(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm"));
    }


    @Override
    public List<MedicalDTO> dynamicCascade(String medicalId, String dataRelationIds, String numberValue) {
        List<MedicalDTO> result = new ArrayList<>();
        List<Element> tempList = new ArrayList<>();
        List<Element> medicalList = nurseFileMapper.getMedicalList(medicalId, dataRelationIds, numberValue);

        medicalList.stream().forEach(temp -> {
            if (com.haoze.common.enumeration.StateEnum.MEDICAL_MAIN_TYPE.getValue().equals(temp.getType())) {
                getMedical(tempList, temp);
            } else {
                tempList.add(temp);
            }
        });

        tempList.stream().forEach(element -> {
            MedicalDTO dto = new MedicalDTO();
            dto.setElement(element);
            SelvalueDTO selDto = new SelvalueDTO();
            selDto.setDataCode(element.getDataCode());
            if (com.haoze.common.enumeration.StateEnum.SIMPLE_SEL.getValue().equals(element.getType())
                    || com.haoze.common.enumeration.StateEnum.MULTI_SEL.getValue().equals(element.getType())) {
                if (org.springframework.util.StringUtils.hasLength(element.getDataCode())) {
                    List<Map<String, String>> options = nurseFileMapper.getSelectedOptions(element.getId(), element.getDataCode());
                    selDto.setDataValue(options.stream().map(p -> org.springframework.util.StringUtils.isEmpty(p.get("dataText")) ? "" : p.get("dataText")).collect(Collectors.joining(",")));
                    selDto.setShowText(options.stream().map(p -> org.springframework.util.StringUtils.isEmpty(p.get("showText")) ? p.get("dataText") : p.get("showText")).collect(Collectors.joining(",")));
                } else {
                    selDto.setDataValue(element.getDataValue());
                }
            } else {
                selDto.setDataValue(element.getDataValue());
            }
            dto.setFileIndexDataEntity(selDto);
            result.add(dto);
        });
        return result;
    }


    private List<Element> getMedical(List<Element> list, Element element) {
        List<Element> tempList = nurseFileMapper.getMedicalChildren(element.getId(), "0", "0");
        tempList.stream().forEach(temp -> {
            if (com.haoze.common.enumeration.StateEnum.MEDICAL_MAIN_TYPE.getValue().equals(temp.getType())) {
                getMedical(tempList, temp);
            } else {
                list.add(temp);
            }
        });
        return list;
    }


    @Override
    public Result getModifyLocation(String recordType, String inpatNum) {
        NurseFileTypeEnum typeEnum = null;
        for (NurseFileTypeEnum enumTemp : NurseFileTypeEnum.values()) {
            if (recordType.equals(enumTemp.getEnumValue())) {
                typeEnum = enumTemp;
                break;
            }
        }
        if (typeEnum == null) {
            return ResultGenerator.genOkResult();
        }
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        NurseModifyLocationEntity temp = new NurseModifyLocationEntity();
        temp.setRecordType(recordType);
        temp.setUserId(userId);
        NurseModifyLocationEntity entity = nurseModifyLocationMapper.selectOne(temp);
        String modifyLocation = "";
        if (entity != null) {
            modifyLocation = entity.getModifyLocation();
        }
        String tplId = nurseFileMapper.queryTplIdByVarCode(typeEnum.getVarCode());
        List<Map<String, String>> modifyLocationList = nurseFileMapper.getModifyLocation(tplId, modifyLocation);
        return ResultGenerator.genOkResult(modifyLocationList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result getRemark(String recordType, String inpatNum) {

        NurseFileDataEntity dataEntity = nurseFileDataMapper.queryOnlyRecord(recordType, inpatNum);
        if (dataEntity != null) {

            String fileDataId = dataEntity.getFileDataId();
            // 存在记录
            NurseDto nurseDto = new NurseDto();
            NurseFileDataEntity fileDataEntity = nurseFileDataMapper.queryOneDataRecord(fileDataId);
            nurseDto.setFileDataId(fileDataId);
            nurseDto.setRecordTime(fileDataEntity.getRecordTime());

            List<NurseFileData> datalist = recursiveQueryFileData(fileDataId, "0", "0", false);
            List<NurseFileData> nurseFileDataList = buildTreeData(datalist, "0");

            nurseDto.setEmrFileDataList(nurseFileDataList);

            return ResultGenerator.genOkResult(nurseDto);

        } else {
            NurseFileIndexEntity fileIndexEntity = nurseFileIndexMapper.queryIndexByRecordType(recordType, inpatNum);
            if (fileIndexEntity == null) {
                Result result = createNewRecord(inpatNum, recordType);
                NurseDto nurseDto = (NurseDto) result.getData();
                NurseFile nurseFile = new NurseFile();
                nurseFile.setEmrFileDataList(nurseDto.getEmrFileDataList());
                nurseFile.setInpatNum(inpatNum);
                nurseFile.setRecordType(recordType);
                nurseFile.setBedNo(nurseDto.getBedNo());
                nurseFile.setRecordTime(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm"));
                save(nurseFile);
            }

            return buildRemark(recordType, inpatNum);

        }
    }


    private Result buildRemark(String recordType, String inpatNum) {
        NurseFileDataEntity dataEntity = nurseFileDataMapper.queryOnlyRecord(recordType, inpatNum);
        if (dataEntity != null) {

            String fileDataId = dataEntity.getFileDataId();
            // 存在记录
            NurseDto nurseDto = new NurseDto();
            NurseFileDataEntity fileDataEntity = nurseFileDataMapper.queryOneDataRecord(fileDataId);
            nurseDto.setFileDataId(fileDataId);
            nurseDto.setRecordTime(fileDataEntity.getRecordTime());

            List<NurseFileData> datalist = recursiveQueryFileData(fileDataId, "0", "0", false);
            List<NurseFileData> nurseFileDataList = buildTreeData(datalist, "0");

            nurseDto.setEmrFileDataList(nurseFileDataList);

            return ResultGenerator.genOkResult(nurseDto);

        } else {
            String tplId = "";
            if (recordType.equals(NurseFileTypeEnum.CareRemark.getEnumValue())) {
                // 护理记录单备注
                tplId = nurseFileMapper.queryTplIdByVarCode("ck_careremark");
            } else if (recordType.equals(NurseFileTypeEnum.NewCareRemark.getEnumValue())) {
                // 新生儿护理记录单备注
                tplId = nurseFileMapper.queryTplIdByVarCode("ck_newcareremark");
            } else if (recordType.equals(NurseFileTypeEnum.ChildCareRemark.getEnumValue())) {
                // 儿科护理记录单备注
                tplId = nurseFileMapper.queryTplIdByVarCode("ck_childcareremark");
            } else {
                // 其他
                return ResultGenerator.genOkResult(new ArrayList<>());
            }
            List<EmrTemplateDetailEntity> tplDetails = nurseFileMapper.queryTplDetailByTplId(tplId);

            List list = getNurseFileData(tplDetails, inpatNum, recordType);
            List<NurseFileData> fileDatalist = createBuildTreeData(list, null);

            // 模板会多包装一层，提出
            NurseFileData parentNurseFileData = fileDatalist.get(0);

            NurseDto nurseDto = new NurseDto();
            nurseDto.setFileDataId("");
            nurseDto.setRecordTime(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm"));
            nurseDto.setEmrFileDataList(parentNurseFileData.getEmrFileDataList());

//            NursePatientMsgDTO dto = nursePatientMapper.getPatientInfo(inpatNum);
//            // 返回床号病区科室信息
//            Map<String, String> locationMap = getInHospitalLocationInfo(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm"), inpatNum, dto.getBedNo());
//            String wardName = nurseFileMapper.queryDeptNameById(locationMap.get("wardId"));
//            String deptName = nurseFileMapper.queryDeptNameById(locationMap.get("deptId"));
//            String bedNo = locationMap.get("bedNo");
//
//            nurseDto.setCurrBed(bedNo == null ? "0" : bedNo);
//            nurseDto.setCurrWard(wardName == null ? "" : wardName);
//            nurseDto.setCurrDept(deptName == null ? "" : deptName);
//            nurseDto.setBedNo(bedNo == null ? "0" : bedNo);
//            // 处理床号,当出院病人床号为0时显示最近一次护理记录单中记录的床号
//            if ("0".equals(nurseDto.getBedNo())) {
//                // 获取记录时间最近的护理记录，从中获取床号
//                bedNo = nurseFileMapper.getLatestBedNo(inpatNum);
//                if (StringUtils.isNotEmpty(bedNo)) {
//                    nurseDto.setBedNo(bedNo);
//                    nurseDto.setCurrBed(bedNo);
//                }
//
//            }
            nurseDto.setFileIndexId("");
            return ResultGenerator.genOkResult(nurseDto);
        }
    }


    @Override
    public Result searchName(String searchName) {
        List<Map<String, String>> list = searchBlood(searchName);
        return ResultGenerator.genOkResult(list);
    }

    @Override
    public Result delRemark(String tplDetailId, String recordType, String inpatNum, String name) {
        // 判断是否默认选项，如果默认选项则不能删除
        String returnDetailId = nurseFileMapper.queryTplDataValueContentName(tplDetailId, name);
        if (StringUtils.isNotBlank(returnDetailId) && returnDetailId.equals(tplDetailId)) {
            return ResultGenerator.genFailedResult("默认选项，不可删除");
        }
        // 判断是否有记录保存，返回保存的记录
        List<Map<String, String>> qouteList = nurseFileDataDetailMapper.queryRemarkQouteList(inpatNum, name);
        if (ArrayUtils.isNotEmpty(qouteList.toArray())) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("qouteList", qouteList);
            return ResultGenerator.genOkResult(resultMap);
        }
        // 如果非默认选项又没有记录保存那么可以删除
        NurseFileDataDetailEntity nurseFileDataDetailEntity = nurseFileDataDetailMapper.queryOneDetailData(inpatNum, tplDetailId);
        if (nurseFileDataDetailEntity != null) {
            String[] dataCodes = nurseFileDataDetailEntity.getDataCode().split(",");
            String[] dataValues = nurseFileDataDetailEntity.getDataValue().split(",");
            StringBuilder dataCode = new StringBuilder();
            StringBuilder dataValue = new StringBuilder();
            for (int i = 0; i < dataCodes.length; i++) {
                String code = dataCodes[i];
                String value = dataValues[i];
                if (!value.equals(name)) {
                    if (0 == i) {
                        dataCode.append(code);
                        dataValue.append(value);
                    } else {
                        dataCode.append(",").append(code);
                        dataValue.append(",").append(value);
                    }
                }
            }

            nurseFileDataDetailMapper.updateDataCodeAndValue(nurseFileDataDetailEntity.getDataVersion() + 1, dataCode.toString(), dataValue.toString(), nurseFileDataDetailEntity.getFileDataDetailId());
            return ResultGenerator.genOkResult("删除成功");

        }
        return null;
    }


    @Override
    public Result getAssess(String varCode) {
        List<Map<String, String>> list = nurseFileMapper.queryCommonDictionryValues(varCode);
        if (list != null) {
            return ResultGenerator.genOkResult(list);
        }
        return ResultGenerator.genOkResult(new ArrayList<>());
    }

    @Override

    public Result ownTemplate(String basicValueId) {
        Map<String, String> map = nurseFileMapper.queryOwnTemplate(basicValueId);
        if (map == null) {
            map = new HashMap<>();
            map.put("ownNode", "0");
        }
        return ResultGenerator.genOkResult(map);
    }

    /*被授权的医疗术语目录id*/
    private static final String authCatalogId = "f5bd17996d2c4785ad937a0c93179a41";

    @Override
    public Result medicalTree(RoleTypeEntity roleTypeEntity) {
        if (StringUtils.isBlank(roleTypeEntity.getPid())) {
            roleTypeEntity.setPid("0");
        }
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        List<Map<String, String>> data = userDeptService.getDeptListById(userId);
        roleTypeEntity.setDeptIds(data.stream().map(map -> map.get("deptId")).collect(Collectors.toList()));
        List<ListTreeEntity> entities = new ArrayList<>();
        //无检索值
        if (StringUtils.isBlank(roleTypeEntity.getQueryString())) {
            entities.addAll(emrMedicalCatalogMapper.listChildren(roleTypeEntity));
        } else {
            List<String> idList = emrMedicalCatalogMapper.queryCatalogAndMedicalIds(roleTypeEntity);
            if (idList.size() > 999) { // where in 查询条件不能超过999个参数
                idList = idList.subList(0, 999);
            }
            if (!idList.isEmpty()) {
                entities.addAll(emrMedicalCatalogMapper.getCatalogAndMedicals(idList));
            }
        }
        List<Tree<ListTreeEntity>> trees = new ArrayList<>();
        for (ListTreeEntity entity : entities) {
            Tree<ListTreeEntity> tree = new Tree<>();
            tree.setId(entity.getId());
            tree.setParentId(entity.getPid());
            tree.setText(entity.getName());
            tree.setMedicalType(entity.getMedicalType());
            tree.setType(entity.getMedicalType());
            trees.add(tree);
        }
        List<Tree<ListTreeEntity>> t = buildTree(trees);
        List<Tree<ListTreeEntity>> finalCatalogList = new ArrayList<>();
        finalCatalogList.addAll(t);
        List<Tree<ListTreeEntity>> authTrees = new ArrayList<>();
        if (StateEnum.ROLE_TYPE_DEPARTMENT.getValue().equals(roleTypeEntity.getRoleType()) && "0".equals(roleTypeEntity.getPid())) {
            Tree<ListTreeEntity> tree = new Tree<>();
            tree.setId(authCatalogId);
            tree.setText("被授权的医疗术语目录");
            tree.setChildren(new ArrayList<>());
            finalCatalogList.add(tree);
        }
        if (authCatalogId.equals(roleTypeEntity.getPid())) {
            List<ListTreeEntity> authCatalog = emrMedicalCatalogMapper.findMedicalCatalogByDept(roleTypeEntity);
            for (ListTreeEntity entity : authCatalog) {
                Tree<ListTreeEntity> tree2 = new Tree<>();
                tree2.setId(entity.getId());
                tree2.setParentId(entity.getPid());
                tree2.setText(entity.getName());
                tree2.setMedicalType(entity.getMedicalType());
                tree2.setType(entity.getMedicalType());
                authTrees.add(tree2);
            }
            return ResultGenerator.genOkResult(authTrees);
        }
        return ResultGenerator.genOkResult(finalCatalogList);
    }

    private <T> List<Tree<T>> buildTree(List<Tree<T>> nodes) {
        if (nodes == null) {
            return null;
        }
        List<Tree<T>> topNodes = new ArrayList<>();

        for (Tree<T> children : nodes) {

            String pid = children.getParentId();
            if (pid == null || "0".equals(pid)) {
                topNodes.add(children);
                continue;
            }

            for (Tree<T> parent : nodes) {
                String id = parent.getId();
                if (id != null && id.equals(pid)) {
                    parent.getChildren().add(children);
                    children.setHasParent(true);
                    parent.setChildren(true);
                    continue;
                }
            }
        }
        return topNodes;
    }

    @Override
    public Result getFormListByUser() {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        List<Map<String, String>> data = nurseFileIndexMapper.getFromListByUser(userId);
        return ResultGenerator.genOkResult(data);
    }

    @Override
    public Result wardDeptSummary(WardSummaryDTO dto) {
        String beginTime = dto.getBeginTime();
        String endTime = dto.getEndTime();
        if (StringUtils.isBlank(beginTime)) {
            beginTime = "1970-01-01";
        }
        if (StringUtils.isBlank(endTime)) {
            endTime = DateUtil.dateToString(new Date(), "yyyy-MM-dd");
        }
        dto.setBeginTime(beginTime + " 00:00:00");
        dto.setEndTime(endTime + " 23:59:59");
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<Map<String, String>> patientSum = nursePatientMapper.getPatientSummary(dto);
        PageInfo<Map<String, String>> pageInfo = new PageInfo<>(patientSum);
        for (Map map : pageInfo.getList()) {
            if ("总计".equals(map.get("status").toString())) {
                map.put("STATUS", dto.getStatus());
                map.put("inType", dto.getInType());
            }
            if (map.get("inType") != null && "小计".equals(map.get("inType").toString())) {
                map.put("INTYPE", dto.getInType());
            }
        }
        return ResultGenerator.genOkResult(pageInfo);
    }

    @Override
    public Result wardDeptSummaryDetail(WardSummaryDTO dto) {
        String timeRange = dto.getTimeRange();
        String beginTime = timeRange.split("至")[0];
        String endTime = timeRange.split("至")[1];
        dto.setBeginTime(beginTime + " 00:00:00");
        dto.setEndTime(endTime + " 23:59:59");
//        if("总计".equals(dto.getStatus())){
//            dto.setStatus("1,2,3");
//        }
//        if("小计".equals(dto.getInType())){
//            dto.setInType("");
//        }
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<Map<String, String>> patientSum = nursePatientMapper.wardDeptSummaryDetail(dto);
        PageInfo<Map<String, String>> pageInfo = new PageInfo<>(patientSum);
        return ResultGenerator.genOkResult(pageInfo);
    }

    @Override
    public Result list(Map param) {
        int page = 1;
        int pageSize = 10;
        if (param.get("page") != null) {
            page = Integer.valueOf(param.get("page").toString());
        }
        if (param.get("pageSize") != null) {
            pageSize = Integer.valueOf(param.get("pageSize").toString());
        }
        PageHelper.startPage(page, pageSize);
        Condition condition = new Condition(MessageEntity.class);
        condition.orderBy("createTime").desc();
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("msgType", param.get("msgType") == null ? MessageEnum.MSG_TYPE_ONE.getIndex() : param.get("msgType"));
        criteria.andEqualTo("sysType", param.get("sysType") == null ? MessageEnum.SYS_TYPE_TWO.getIndex() : param.get("sysType"));
        List<MessageEntity> list = messageMapper.selectByCondition(condition);
        PageInfo<MessageEntity> pageInfo = new PageInfo(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    @Override
    public Result getCareUnit() {
        List<Map<String, String>> querSelectionsList = nurseElementMapper.queryNoSearchSelections("c817935839544e539d28897df46d23d9", "", "", "", "0");
        if (ArrayUtils.isEmpty(querSelectionsList.toArray())) {
            return ResultGenerator.genFailedResult("获取护理单位失败");
        }
        return ResultGenerator.genOkResult(querSelectionsList);
    }
}
